@reason-machines/cli-linux-x64 0.2.504 → 0.2.505

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 (167) hide show
  1. package/THIRD_PARTY_NOTICES.txt +7 -8
  2. package/bin/reason +2 -2
  3. package/bin/runtime/srt/sandbox-runtime.mjs +52 -52
  4. package/bin/vm-hands/api-credentials-23k36ayh.js +2 -0
  5. package/bin/vm-hands/api-jd29p2kc.js +2 -0
  6. package/bin/vm-hands/ask-relay-zpp0rkhg.js +4 -0
  7. package/bin/vm-hands/connect-cli-xyxgcg6z.js +2 -0
  8. package/bin/vm-hands/credentials-byna24dv.js +2 -0
  9. package/bin/vm-hands/custom-endpoint-device-p2agcsk0.js +2 -0
  10. package/bin/vm-hands/desktop-account-z16mmkxg.js +2 -0
  11. package/bin/vm-hands/device-workspace-y0tk3ne8.js +2 -0
  12. package/bin/vm-hands/hands-worker-source-0qa16xzj.js +2 -0
  13. package/bin/vm-hands/index-h6xkz48h.js +12818 -0
  14. package/bin/vm-hands/install-receipt-nnragt7p.js +2 -0
  15. package/bin/vm-hands/local-automation-xbpca0f3.js +2 -0
  16. package/bin/vm-hands/local-capabilities-30m8pzpv.js +2 -0
  17. package/bin/vm-hands/local-desktop-users-gxfywsan.js +2 -0
  18. package/bin/vm-hands/local-display-mac-n236gkpe.js +2 -0
  19. package/bin/vm-hands/local-display-session-ddafdm8k.js +2 -0
  20. package/bin/vm-hands/local-display-video-gha54xwa.js +2 -0
  21. package/bin/vm-hands/local-managed-process-0zwxyqxd.js +2 -0
  22. package/bin/vm-hands/local-pty-session-w1yrmjm0.js +2 -0
  23. package/bin/vm-hands/managed-runtime-8y90twae.js +2 -0
  24. package/bin/vm-hands/network-contract-v0fkg94d.js +2 -0
  25. package/bin/vm-hands/network-sign-in-3dkdkh3a.js +34 -0
  26. package/bin/vm-hands/package-z2dk6xva.js +2 -0
  27. package/bin/vm-hands/permissions-ga1ax8wd.js +2 -0
  28. package/bin/vm-hands/reason-hands-protocol-vzgxd159.js +2 -0
  29. package/bin/vm-hands/serve-service-42nqanvr.js +2 -0
  30. package/bin/vm-hands/status-m0g7k47a.js +96 -0
  31. package/bin/vm-hands/version-ye6800p2.js +2 -0
  32. package/bin/vm-hands/vm-hands-entry-lite-00y3kn86.js +7 -0
  33. package/bin/vm-hands/vm-hands-entry-lite-0572m6cr.js +344 -0
  34. package/bin/vm-hands/vm-hands-entry-lite-07q2xvk1.js +5 -0
  35. package/bin/vm-hands/vm-hands-entry-lite-0a4cy8gw.js +5 -0
  36. package/bin/vm-hands/vm-hands-entry-lite-1nj03gbj.js +4 -0
  37. package/bin/vm-hands/vm-hands-entry-lite-26xb026c.js +3 -0
  38. package/bin/vm-hands/vm-hands-entry-lite-33h8294z.js +3 -0
  39. package/bin/vm-hands/vm-hands-entry-lite-3882raa5.js +3 -0
  40. package/bin/vm-hands/vm-hands-entry-lite-3rg3znp8.js +3 -0
  41. package/bin/vm-hands/vm-hands-entry-lite-4swa18qz.js +10 -0
  42. package/bin/vm-hands/vm-hands-entry-lite-56v9haps.js +3 -0
  43. package/bin/vm-hands/vm-hands-entry-lite-6x5pj2y0.js +4 -0
  44. package/bin/vm-hands/{vm-hands-entry-lite-fcvf8md1.js → vm-hands-entry-lite-8p8hz0j1.js} +2 -2
  45. package/bin/vm-hands/vm-hands-entry-lite-8twscwtw.js +112 -0
  46. package/bin/vm-hands/vm-hands-entry-lite-8xe0wzp9.js +3 -0
  47. package/bin/vm-hands/vm-hands-entry-lite-ah2ep922.js +4 -0
  48. package/bin/vm-hands/vm-hands-entry-lite-b0p8f295.js +52 -0
  49. package/bin/vm-hands/{vm-hands-entry-lite-77j164ps.js → vm-hands-entry-lite-b7wy89y0.js} +54 -54
  50. package/bin/vm-hands/vm-hands-entry-lite-c5gt0086.js +3 -0
  51. package/bin/vm-hands/{vm-hands-entry-lite-wrvz9jxy.js → vm-hands-entry-lite-c8bf82tx.js} +2 -2
  52. package/bin/vm-hands/vm-hands-entry-lite-dgmap6z4.js +5 -0
  53. package/bin/vm-hands/vm-hands-entry-lite-dhqmbqsh.js +9 -0
  54. package/bin/vm-hands/vm-hands-entry-lite-e1xjfj57.js +3 -0
  55. package/bin/vm-hands/vm-hands-entry-lite-e4hwb89r.js +66 -0
  56. package/bin/vm-hands/vm-hands-entry-lite-g6r5xrk0.js +105 -0
  57. package/bin/vm-hands/vm-hands-entry-lite-ghhpgt3v.js +3 -0
  58. package/bin/vm-hands/vm-hands-entry-lite-h5smacqn.js +3 -0
  59. package/bin/vm-hands/vm-hands-entry-lite-jd31as70.js +3 -0
  60. package/bin/vm-hands/vm-hands-entry-lite-k9n1pk42.js +4 -0
  61. package/bin/vm-hands/vm-hands-entry-lite-kqbats5n.js +3 -0
  62. package/bin/vm-hands/vm-hands-entry-lite-p9fwt68c.js +42 -0
  63. package/bin/vm-hands/vm-hands-entry-lite-pkk555dx.js +3 -0
  64. package/bin/vm-hands/vm-hands-entry-lite-pmw3ycgc.js +5 -0
  65. package/bin/vm-hands/vm-hands-entry-lite-q9g11dbj.js +3 -0
  66. package/bin/vm-hands/vm-hands-entry-lite-r374pchj.js +9 -0
  67. package/bin/vm-hands/vm-hands-entry-lite-r665z809.js +4 -0
  68. package/bin/vm-hands/vm-hands-entry-lite-rck5h8fr.js +3 -0
  69. package/bin/vm-hands/vm-hands-entry-lite-rj8yq6gp.js +3 -0
  70. package/bin/vm-hands/{vm-hands-entry-lite-c11fg8gx.js → vm-hands-entry-lite-s8ty42st.js} +9 -5
  71. package/bin/vm-hands/vm-hands-entry-lite-s8zfzv0k.js +6 -0
  72. package/bin/vm-hands/vm-hands-entry-lite-tafgty5k.js +4 -0
  73. package/bin/vm-hands/vm-hands-entry-lite-tbdcmq09.js +3 -0
  74. package/bin/vm-hands/vm-hands-entry-lite-td309c1y.js +5 -0
  75. package/bin/vm-hands/vm-hands-entry-lite-v0bp1v66.js +128 -0
  76. package/bin/vm-hands/vm-hands-entry-lite-v0k8b768.js +452 -0
  77. package/bin/vm-hands/vm-hands-entry-lite-v4r1fggm.js +3 -0
  78. package/bin/vm-hands/vm-hands-entry-lite-vqr3zrqr.js +539 -0
  79. package/bin/vm-hands/vm-hands-entry-lite-wbfmc0xn.js +3 -0
  80. package/bin/vm-hands/vm-hands-entry-lite-x3pbyg92.js +3 -0
  81. package/bin/vm-hands/{vm-hands-entry-lite-rfz60hb3.js → vm-hands-entry-lite-xd2dn3n8.js} +2 -2
  82. package/bin/vm-hands/vm-hands-entry-lite-yqn8h1p0.js +3 -0
  83. package/bin/vm-hands/vm-hands-entry-lite-zj3hb5jk.js +127 -0
  84. package/bin/vm-hands/vm-hands-entry-lite-zz8tr0bm.js +12 -0
  85. package/bin/vm-hands/vm-hands-entry-lite.js +1 -3
  86. package/bin/vm-hands/vm-hands-executor-6tncheya.js +12 -0
  87. package/bin/vm-hands/vm-hands-op-runner-s1ghsym7.js +2 -0
  88. package/bin/vm-hands/vm-hands-runtime-k6egwk2t.js +4 -0
  89. package/bin/vm-hands/worker-preview-readiness-wh0yg1dz.js +2 -0
  90. package/bin/vm-hands/worker-sandbox-s054x4zw.js +2 -0
  91. package/package.json +1 -1
  92. package/bin/vm-hands/api-credentials-gnefpvc1.js +0 -2
  93. package/bin/vm-hands/api-mjzanhf1.js +0 -2
  94. package/bin/vm-hands/connect-cli-dy7mdehx.js +0 -2
  95. package/bin/vm-hands/credentials-drj5ktpt.js +0 -2
  96. package/bin/vm-hands/custom-endpoint-device-j1x988g0.js +0 -2
  97. package/bin/vm-hands/desktop-account-4525j7h3.js +0 -2
  98. package/bin/vm-hands/device-workspace-pt07525s.js +0 -2
  99. package/bin/vm-hands/fsevents-8zxmv89w.js +0 -2
  100. package/bin/vm-hands/hands-worker-source-atg5dc7b.js +0 -2
  101. package/bin/vm-hands/index-ttmxy9nd.js +0 -12818
  102. package/bin/vm-hands/install-receipt-6v65enmf.js +0 -2
  103. package/bin/vm-hands/local-automation-wfa3dpbs.js +0 -2
  104. package/bin/vm-hands/local-capabilities-3v7x217d.js +0 -2
  105. package/bin/vm-hands/local-desktop-users-ar6xpadb.js +0 -2
  106. package/bin/vm-hands/local-display-mac-fnp3317m.js +0 -2
  107. package/bin/vm-hands/local-display-session-2064d8k8.js +0 -2
  108. package/bin/vm-hands/local-display-video-1hxqy3xj.js +0 -2
  109. package/bin/vm-hands/local-managed-process-trmeeyh2.js +0 -2
  110. package/bin/vm-hands/local-pty-session-5yh2a63r.js +0 -2
  111. package/bin/vm-hands/managed-runtime-hhk63f61.js +0 -2
  112. package/bin/vm-hands/network-contract-rzw769gw.js +0 -2
  113. package/bin/vm-hands/package-r7sgmw4t.js +0 -2
  114. package/bin/vm-hands/permissions-xwyhbnjc.js +0 -2
  115. package/bin/vm-hands/reason-hands-protocol-8fgk2s53.js +0 -2
  116. package/bin/vm-hands/serve-service-aye42qtb.js +0 -2
  117. package/bin/vm-hands/status-qtm9gb55.js +0 -10
  118. package/bin/vm-hands/version-gnb213c3.js +0 -2
  119. package/bin/vm-hands/vm-hands-entry-lite-0y9n06b6.js +0 -14
  120. package/bin/vm-hands/vm-hands-entry-lite-38g65s5x.js +0 -3
  121. package/bin/vm-hands/vm-hands-entry-lite-3sjkzhf6.js +0 -3
  122. package/bin/vm-hands/vm-hands-entry-lite-545m8hm0.js +0 -3
  123. package/bin/vm-hands/vm-hands-entry-lite-57v7y0km.js +0 -105
  124. package/bin/vm-hands/vm-hands-entry-lite-5gevvgec.js +0 -2
  125. package/bin/vm-hands/vm-hands-entry-lite-5tbntcyq.js +0 -42
  126. package/bin/vm-hands/vm-hands-entry-lite-61y11rrd.js +0 -3
  127. package/bin/vm-hands/vm-hands-entry-lite-6x1an7es.js +0 -7
  128. package/bin/vm-hands/vm-hands-entry-lite-7777m86y.js +0 -3
  129. package/bin/vm-hands/vm-hands-entry-lite-87vmbt38.js +0 -3
  130. package/bin/vm-hands/vm-hands-entry-lite-8e5djf5y.js +0 -5
  131. package/bin/vm-hands/vm-hands-entry-lite-8wcyveeh.js +0 -2
  132. package/bin/vm-hands/vm-hands-entry-lite-e1z3y9rs.js +0 -4
  133. package/bin/vm-hands/vm-hands-entry-lite-eabever7.js +0 -112
  134. package/bin/vm-hands/vm-hands-entry-lite-ewr54tpc.js +0 -3
  135. package/bin/vm-hands/vm-hands-entry-lite-ex69qn9q.js +0 -2
  136. package/bin/vm-hands/vm-hands-entry-lite-f62fvme8.js +0 -5
  137. package/bin/vm-hands/vm-hands-entry-lite-f69t48dj.js +0 -4
  138. package/bin/vm-hands/vm-hands-entry-lite-gvjffc5t.js +0 -65
  139. package/bin/vm-hands/vm-hands-entry-lite-hmaazqdr.js +0 -2
  140. package/bin/vm-hands/vm-hands-entry-lite-kq7hrjch.js +0 -128
  141. package/bin/vm-hands/vm-hands-entry-lite-mcjca0ez.js +0 -3
  142. package/bin/vm-hands/vm-hands-entry-lite-mk5ayds8.js +0 -3
  143. package/bin/vm-hands/vm-hands-entry-lite-mqzr55mw.js +0 -126
  144. package/bin/vm-hands/vm-hands-entry-lite-ncbzy69k.js +0 -4
  145. package/bin/vm-hands/vm-hands-entry-lite-np07qyeq.js +0 -3
  146. package/bin/vm-hands/vm-hands-entry-lite-nqdstx24.js +0 -3
  147. package/bin/vm-hands/vm-hands-entry-lite-psywfz8m.js +0 -9
  148. package/bin/vm-hands/vm-hands-entry-lite-pydgnx8a.js +0 -539
  149. package/bin/vm-hands/vm-hands-entry-lite-qpdpzg8g.js +0 -3
  150. package/bin/vm-hands/vm-hands-entry-lite-qt71vz32.js +0 -52
  151. package/bin/vm-hands/vm-hands-entry-lite-qxsqx6hz.js +0 -2
  152. package/bin/vm-hands/vm-hands-entry-lite-qy9xg6em.js +0 -3
  153. package/bin/vm-hands/vm-hands-entry-lite-rmabryke.js +0 -452
  154. package/bin/vm-hands/vm-hands-entry-lite-rzr2ncf5.js +0 -5
  155. package/bin/vm-hands/vm-hands-entry-lite-sss0m3yn.js +0 -3
  156. package/bin/vm-hands/vm-hands-entry-lite-swrymqj9.js +0 -3
  157. package/bin/vm-hands/vm-hands-entry-lite-tebh7dcm.js +0 -6
  158. package/bin/vm-hands/vm-hands-entry-lite-txd50spx.js +0 -3
  159. package/bin/vm-hands/vm-hands-entry-lite-wg0cykk2.js +0 -9
  160. package/bin/vm-hands/vm-hands-entry-lite-x39tmj7j.js +0 -5
  161. package/bin/vm-hands/vm-hands-entry-lite-xdjrdkh2.js +0 -4
  162. package/bin/vm-hands/vm-hands-entry-lite-yretc2th.js +0 -3
  163. package/bin/vm-hands/vm-hands-executor-8c542krk.js +0 -12
  164. package/bin/vm-hands/vm-hands-op-runner-88e10ptt.js +0 -2
  165. package/bin/vm-hands/vm-hands-runtime-njh3th64.js +0 -4
  166. package/bin/vm-hands/worker-preview-readiness-7xtgxsar.js +0 -2
  167. package/bin/vm-hands/worker-sandbox-s9pyac8p.js +0 -2
@@ -0,0 +1,539 @@
1
+ // @bun
2
+ import{Fb as y6,Hb as h6,Ib as m6}from"./vm-hands-entry-lite-00y3kn86.js";import{Lb as G7,Mb as U7,Ob as X7,Pb as W7,Qb as w4,Rb as z7,Sb as F7,Vb as A3}from"./vm-hands-entry-lite-ah2ep922.js";import{$c as V7,Dc as $7,Ec as J7,Gc as Z7,Hc as Q7,Ic as H4,Jc as C4,Lc as K7,Nc as d4,Oc as x0,Pc as h0,Qc as t1,Tc as B7,Wc as l4,ic as l6,jc as s6,lc as c6,mc as k3,nc as n6,oc as r6,pc as a6,qc as i6,sc as o6,tc as t6,zc as e6}from"./vm-hands-entry-lite-v0k8b768.js";import{ed as x6}from"./vm-hands-entry-lite-s8zfzv0k.js";import{kd as L3,ld as I3,sd as O3}from"./vm-hands-entry-lite-b7wy89y0.js";import{Cd as u6,Dd as p6,Ed as d6}from"./vm-hands-entry-lite-dhqmbqsh.js";import{Hd as $1}from"./vm-hands-entry-lite-3882raa5.js";import{Id as f6}from"./vm-hands-entry-lite-tbdcmq09.js";import{$d as c3,Qd as Q2,Rd as K2,Sd as p3,Ud as d3,Wd as l3,Xd as s3,be as b6}from"./vm-hands-entry-lite-8xe0wzp9.js";import{ke as $2,ne as f7,we as x7}from"./vm-hands-entry-lite-s8ty42st.js";import{$f as G6,Af as b1,Ag as G8,Bg as U8,Cg as X8,Df as $8,Dg as W8,Eg as z8,Ff as f1,Fg as F8,Gg as Y8,Hf as l5,Hg as N8,If as s5,Ig as H8,Jg as C8,Mf as c5,Nf as n5,Of as r5,Pf as a5,Qf as i5,Rf as o5,Sf as t5,Tf as e5,Uf as $6,Vf as J6,Wf as Z6,Xf as Q6,Yf as K6,Zf as B6,_f as V6,ag as U6,bg as X6,cg as W6,dg as z6,hg as F6,ig as Y6,jg as N6,kf as I1,kg as H6,lf as O1,lg as C6,mf as g3,mg as w6,nf as W2,ng as D6,of as d5,pf as E3,qf as U4,rf as X4,sf as D0,tg as J8,ug as Z8,vg as Q8,wf as Y0,wg as K8,xg as B8,yg as V8,zf as d}from"./vm-hands-entry-lite-p9fwt68c.js";import{Ng as D7,Qg as s8,Sg as i1}from"./vm-hands-entry-lite-v0bp1v66.js";import{bh as E5,fh as n8,gh as T5}from"./vm-hands-entry-lite-zj3hb5jk.js";import{kh as R6,lh as q6}from"./vm-hands-entry-lite-b0p8f295.js";import{Ah as R0,wh as C1,xh as w1,yh as D1,zh as j1}from"./vm-hands-entry-lite-26xb026c.js";import{Bh as M6,Ch as L6,Dh as I6,Eh as O6,Gh as A6,Hh as _6,Jh as P6,Kh as T6}from"./vm-hands-entry-lite-8twscwtw.js";import{Wh as Y7,Xh as N7,Yh as H7,ai as C7,di as w7}from"./vm-hands-entry-lite-rj8yq6gp.js";import{ti as S6}from"./vm-hands-entry-lite-td309c1y.js";import{Mi as v6,zi as M3}from"./vm-hands-entry-lite-1nj03gbj.js";import{vj as e1}from"./vm-hands-entry-lite-k9n1pk42.js";import{mk as l8,nk as j6}from"./vm-hands-entry-lite-56v9haps.js";import{rk as j3,tk as o0,zk as p4}from"./vm-hands-entry-lite-jd31as70.js";import{dl as X}from"./vm-hands-entry-lite-e4hwb89r.js";import{ll as H}from"./vm-hands-entry-lite-v4r1fggm.js";import{ol as D8,ul as g6,vl as E6,wl as k6,yl as k1}from"./vm-hands-entry-lite-kqbats5n.js";import{Al as W4}from"./vm-hands-entry-lite-ghhpgt3v.js";import{Gl as f4}from"./vm-hands-entry-lite-pkk555dx.js";import{request as m7}from"http";import{request as v7}from"https";import{lookup as u7}from"dns/promises";import{isIP as p7}from"net";async function d7($){let J=new URL($.url);return await new Promise((Z,Q)=>{let K=(J.protocol==="https:"?v7:m7)(J,{method:"POST",headers:{...$.headers,"accept-encoding":"identity"},signal:$.signal,timeout:d3},(B)=>Z({response:B,close:()=>{B.destroy(),K.destroy(),B.socket?.destroy()}}));K.once("error",Q),K.once("timeout",()=>K.destroy(Object.assign(Error("custom_endpoint_timeout"),{code:"ETIMEDOUT"}))),K.end($.body)})}var n3=new Set(["ENOTFOUND","EAI_AGAIN","EAI_NONAME","EAI_NODATA","EAI_FAIL","DNSException"]),l7=new Set(["ECONNREFUSED","ETIMEDOUT","ECONNRESET","EHOSTUNREACH","ENETUNREACH","EHOSTDOWN","ENETDOWN","EPIPE","ECONNABORTED","EADDRNOTAVAIL","ConnectionRefused","ConnectionClosed","ConnectionTimedOut","Timeout"]);function r3($,J=0){if(!$||typeof $!=="object"||J>3)return null;let Z=$.code;if(typeof Z==="string"){if(n3.has(Z))return"custom_endpoint_host_not_found";if(l7.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 K=r3(Q,J+1);if(K)return K}return null}async function s7($,J){let Z=r3($),Q=new URL(J).hostname.replace(/^\[|\]$/g,"");if(Z!==null&&Z!=="custom_endpoint_connection_failed"||p7(Q)!==0)return Z;let K;return await Promise.race([u7(Q).then(()=>!0,(V)=>!n3.has(String(V?.code))),new Promise((V)=>{K=setTimeout(()=>V(!0),5000)})]).finally(()=>clearTimeout(K))?Z:"custom_endpoint_host_not_found"}function c7($){for(let J=42;;J++){if(J===127)J=256;let Z=String.fromCodePoint(J);if(!$.includes(Z))return Z}}function n7($,J){let Z=Buffer.from($),Q=Buffer.from(J),K=new Uint32Array(Z.length);for(let V=1,U=0;V<Z.length;V++){while(U&&Z[V]!==Z[U])U=K[U-1];if(Z[V]===Z[U])U++;K[V]=U}let B=0;return(V,U=!1)=>{let z=Buffer.allocUnsafe(V.length*Q.length+B),W=0;for(let G of V){while(B&&Z[B]!==G){let F=K[B-1];W+=Z.copy(z,W,0,B-F),B=F}if(Z[B]===G){if(B++,B===Z.length)W+=Q.copy(z,W),B=0}else z[W++]=G}if(U)W+=Z.copy(z,W,0,B),B=0;return z.subarray(0,W)}}async function a3($){$.signal.throwIfAborted();let J=s3.safeParse($.payload);if(!J.success)throw new H("custom_endpoint_invalid_request","Invalid local model request.");let Z=J.data,Q=c3.parse(await $.credential($.signal));if(!l3(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 K,B,V=0,U=0,z=0,W=c7(Q.apiKey),G=n7(Q.apiKey,W),F=async(N,C)=>{$.signal.throwIfAborted(),await new Promise((L,D)=>{let w=()=>{$.signal.removeEventListener("abort",w),D($.signal.reason)};if($.signal.addEventListener("abort",w,{once:!0}),$.signal.aborted){w();return}Promise.resolve().then(()=>{return $.signal.throwIfAborted(),$.emit(N,C)}).then(()=>{$.signal.removeEventListener("abort",w),L()},(M)=>{$.signal.removeEventListener("abort",w),D(M)})})},Y=async(N)=>{if(V+=N.length,V>K2)throw new H("custom_endpoint_response_too_large","Local model response exceeds the transport limit.");for(let C=0;C<N.length;C+=Q2){if(z>=p3)throw new H("custom_endpoint_response_too_large","Local model response exceeds the chunk limit.");await F(`custom_endpoint.chunk.${z++}`,{eof:!1,data:N.subarray(C,C+Q2).toString("base64")})}};try{let N=await d7({url:Z.url,body:Z.body,signal:$.signal,headers:{...Z.headers,...Q.api==="anthropic-messages"?{"x-api-key":Q.apiKey}:{authorization:`Bearer ${Q.apiKey}`}}});K=N.response,B=N.close;let C=K.statusCode??500;if(C>=300&&C<400)throw new H("custom_endpoint_redirect_refused","Local model redirects are not followed.");if(K.headers["content-encoding"]&&K.headers["content-encoding"]!=="identity")throw new H("custom_endpoint_encoding_unsupported","The local server must honor identity encoding.");let L={};for(let D of["content-type","retry-after","x-request-id","request-id"]){let w=K.headers[D];if(typeof w==="string")L[D]=w.replaceAll(Q.apiKey,W).slice(0,4096)}await F("custom_endpoint.headers",{status:C,statusText:(K.statusMessage??"").replaceAll(Q.apiKey,W).slice(0,256),headers:L});for await(let D of K){$.signal.throwIfAborted();let w=Buffer.isBuffer(D)?D:Buffer.from(D);if(U+=w.length,U>K2)throw new H("custom_endpoint_response_too_large","Local model response exceeds the transport limit.");await Y(G(w))}return await Y(G(Buffer.alloc(0),!0)),await F(`custom_endpoint.chunk.${z}`,{eof:!0}),{bytes:V,chunks:z}}catch(N){if($.signal.throwIfAborted(),N instanceof H)throw N;throw new H((K?null:await s7(N,Z.url))??"custom_endpoint_request_failed","The local model server could not complete the request.")}finally{B?.()}}import{join as i3}from"path";function r7($,J){return $===i3(J,".ara","workspace")||$===i3(J,".reason","workspace")}function o3($,J){let Z=$.filter((Q)=>r7(Q.path,J));return Z.length===1?Z[0].path:null}var a7=/^[a-f0-9]{64}$/;var B2=32,i7=/^\/[^\x00-\x1f\x7f\\]*$/;function Y1($){if(typeof $!=="string"||$.length>4096||!i7.test($))return!1;if($==="/")return!0;return $.split("/").slice(1).every((J)=>J!==""&&J!=="."&&J!=="..")}function N1($,J){let Z=J==="win32"?/^([A-Za-z]):[\\/]*(.*)$/.exec($):null;if(!Z)return $;let Q=Z[2].split(/[\\/]+/).filter(Boolean).join("/");return`/${Z[1].toUpperCase()}:${Q?`/${Q}`:""}`}function H1($){if(!$||typeof $!=="object"||Array.isArray($))return;let J=$;if(!Y1(J.home)||!Array.isArray(J.roots)||J.roots.length>B2)return;let Z=[];for(let Q of J.roots){if(!Q||typeof Q!=="object"||Array.isArray(Q))return;let{path_fingerprint:K,path:B}=Q;if(typeof K!=="string"||!a7.test(K)||!Y1(B))return;Z.push({path_fingerprint:K,path:B})}return{home:J.home,roots:Z}}function o7($){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 t7($){return o7($)??$.email.toLowerCase()}function V2($){let J=/^Co-authored-by:\s*([^<>\r\n]+) <([^<>\s]+)>$/i.exec($.trim());return J?t7({name:J[1],email:J[2]}):$.trim().toLowerCase()}var l0=($)=>$.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/[a-z]/gi,(J)=>`[${J.toLowerCase()}${J.toUpperCase()}]`),e7=[...C1.map(($)=>`/(${$.map(l0).join("/")})(/|$)`),...w1.map(($)=>`/(${$.map(l0).join("/")})(/|$)`),...[...D1].map(($)=>`/(${l0($)})$`),`/${l0(".env.")}[^/]*$`,...j1.map(($)=>`/[^/]*${l0($)}$`)],t3=`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(e7)}.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 J9,spawnSync as Z9}from"child_process";import*as T from"fs";import*as b from"path";import{homedir as Q9}from"os";function e3($,J,Z,Q="gh"){if(!["gh","git"].includes(Q))throw Error("local_device_gh_unavailable");let K=$.realpathSync(Z);if(process.platform==="win32"){let V=(U)=>U.toLowerCase()===K.toLowerCase()||U.toLowerCase().startsWith(K.toLowerCase()+J.sep);for(let U of new Set([process.env.ProgramW6432,process.env.ProgramFiles])){if(!U)continue;try{let z=$.realpathSync(Q==="gh"?`${U}\\GitHub CLI\\gh.exe`:`${U}\\Git\\cmd\\git.exe`);if(!V(z)&&z.toLowerCase().startsWith(U.toLowerCase()+"\\")&&$.statSync(z).isFile())return z}catch{}}throw Error("local_device_gh_unavailable")}let B=Q==="git"&&process.platform==="darwin"?"/Library/Developer/CommandLineTools/usr/bin/git":"/usr/bin/"+Q;for(let V of["/opt/homebrew/bin/"+Q,"/usr/local/bin/"+Q,B])try{let U=$.realpathSync(V);if(U===K||U.startsWith(K+J.sep)||!["/opt/homebrew/","/usr/local/","/usr/bin/",...Q==="git"?["/Library/Developer/CommandLineTools/"]:[]].some((W)=>U.startsWith(W)))continue;let z=$.statSync(U);if(!z.isFile()||(z.mode&18)!==0||![0,process.getuid()].includes(z.uid))continue;return $.accessSync(U,$.constants.X_OK),U}catch{continue}throw Error("local_device_gh_unavailable")}function $4($,J){let Z=1;for(let Q=0;Q<J;Q+=1)if($.charCodeAt(Q)===10)Z+=1;return Z}var J4=[{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 G2($){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 Z4($){return[...new Set($.map((J)=>J.trim()).filter((J)=>J.length>=8))]}function Q4($,J){return[...J.matchAll(new RegExp($.regex.source,`${$.regex.flags}g`))]}function M1($,J=[],Z={}){let Q=[],K=Z.published??new Set,B=Z4(J).filter((V)=>!K.has(V));for(let V of $){let U=G2(V.path);if(!U.valid){Q.push({path:V.path,reason:U.reason??"invalid_path"});continue}let z=V.content??"",W=B.map((G)=>({secret:G,offset:z.indexOf(G)})).filter((G)=>G.offset>=0).sort((G,F)=>G.offset-F.offset);if(W.length>0){let G=[...new Set(W.flatMap((F)=>Z.secretNames?.(F.secret)??[]))];Q.push({path:V.path,reason:"literal_secret_detected",ruleId:"forbidden_secret_value",line:$4(z,W[0].offset),...G.length>0?{secretNames:G}:{}})}for(let G of J4){let F=Q4(G,z).find((Y)=>!K.has(Y[0]));if(F){Q.push({path:V.path,reason:`credential_pattern_detected: ${G.name}`,pattern:G.name,ruleId:G.name,line:$4(z,F.index)});break}}}return{clean:Q.length===0,violations:Q,scannedObjectCount:$.length}}function K4($,J=[]){let Z=Z4(J),Q=new Set;for(let{content:K}of $){for(let B of Z)if(K.includes(B))Q.add(B);for(let B of J4)for(let V of Q4(B,K))Q.add(V[0])}return[...Q]}function $9($,J){let Z=0;for(let Q=$.indexOf(J);Q>=0;Q=$.indexOf(J,Q+J.length))Z+=1;return Z}function B4($,J,Z){let Q=(K,B)=>K.reduce((V,U)=>V+$9(U,B),0);return new Set($.filter((K)=>Q(J,K)<=Q(Z,K)))}var _0=4194304,V0=process.platform==="win32",c0=process.env.SystemRoot??"C:\\Windows",K9=($)=>V0?Z9(b.win32.join(c0,"System32","taskkill.exe"),["/PID",String($),"/T","/F"],{stdio:"ignore",windowsHide:!0}):process.kill(-$,"SIGKILL"),s0=V0?[b.win32.join(c0,"System32"),c0].join(";"):"/usr/bin:/bin:/usr/sbin:/sbin",L1=V0?{SystemRoot:c0,WINDIR:c0}:{},B9=($)=>V0?b.win32.resolve($,"..","..","bin","sh.exe"):"/bin/sh",V4=536870912,U2=/^[a-f0-9]{40}$/,V9=($,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 K;try{K=J9($,J,{cwd:Z.cwd,env:Z.env,...V0?{windowsHide:!0}:{detached:!0},stdio:["pipe","pipe","pipe"]})}catch{Q({status:null,error:Error("spawn_failed"),stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)});return}let B=Buffer.alloc(0),V=Buffer.alloc(0),U,z=!1,W=(N)=>{if(U??=Error(N),K.pid)try{K9(K.pid)}catch{}},G=()=>W("cancelled"),F=setTimeout(()=>W("timeout"),Z.timeout);Z.signal?.addEventListener("abort",G,{once:!0});let Y=(N)=>{if(z)return;z=!0,clearTimeout(F),Z.signal?.removeEventListener("abort",G),Q({status:N,stdout:B,stderr:V,...U?{error:U}:{}})};if(K.stdout.on("data",(N)=>{if(B.length+V.length+N.length>Z.maxBuffer)W("output_limit");else B=Buffer.concat([B,N])}),K.stderr.on("data",(N)=>{if(B.length+V.length+N.length>Z.maxBuffer)W("output_limit");else V=Buffer.concat([V,N])}),K.on("error",()=>{if(W("spawn_failed"),!K.pid)Y(null)}),K.on("close",(N)=>Y(N)),K.stdin.on("error",()=>W("input_failed")),K.stdin.end(Z.input),Z.signal?.aborted)G()}),G9={command:V9,gh:($,J)=>e3(T,b,$,J),home:Q9};function O($){throw Error($)}function X2($,J){let[Z,Q]=V0?[$.toLowerCase(),J.toLowerCase()]:[$,J];return Q===Z||Q.startsWith(Z+b.sep)}function U9($,J){let Z=new Set($.split(/\r?\n/).map(V2));return J.filter((Q)=>{let K=V2(Q);if(Z.has(K))return!1;return Z.add(K),!0})}var X9=new Set(["repoFullName","branch","head","base","defaultBranch","expectedBaseRef","baseSha","remoteHeadSha","expectedHeadSha"]),W9=($)=>JSON.stringify($,(J,Z)=>X9.has(J)?void 0:Z);function G4($,J,Z){let Q=[...new Set($.map((B)=>`${J(B.path)}${B.line?`:${B.line}`:""} (${B.reason==="literal_secret_detected"?`value of ${B.secretNames?.length?B.secretNames.slice(0,3).join(", "):"a session variable"}`:`${B.ruleId??"credential"} credential`})`))].slice(0,10),K=$.some((B)=>B.reason==="literal_secret_detected");O(`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}${K?" 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=G9){let Q=I1.parse($),K="local_device_gh_prepare_setup";try{if(!["darwin","linux","win32"].includes(process.platform))O("local_device_gh_platform_unavailable");J.assertCurrent();let B=T.realpathSync(J.root);if(B===b.parse(B).root)O("local_device_gh_root_unavailable");if(!D0(Q)&&!J.forbiddenSecretValues)O("local_device_gh_secret_scope_unavailable");if(!D0(Q)&&J.readOnly)O("local_device_gh_read_only");if(!D0(Q)){let j=M1([{path:"github-operation",content:W9(Q)}],J.forbiddenSecretValues,J.secretNames?{secretNames:J.secretNames}:{});if(!j.clean)G4(j.violations,()=>`the ${Q.kind} request text`,"Remove it from the pull request text and try again.")}let V=Z.gh(B),U=Z.home(),z=Z.gh(B,"git"),W=J.privateDirectory?T.realpathSync(J.privateDirectory):T.realpathSync(U);if(!D0(Q)&&(!J.privateDirectory||X2(B,W)))O("local_device_gh_private_scope_unavailable");let G={...L1,PATH:V0?[b.dirname(z),s0].join(";"):s0,HOME:U,GH_CONFIG_DIR:V0&&process.env.APPDATA?b.join(process.env.APPDATA,"GitHub CLI"):b.join(U,".config","gh"),GH_PROMPT_DISABLED:"1",GH_PAGER:V0?"":"/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((j)=>process.env[j]?[[j,process.env[j]]]:[])):{}},F=async(j,_,P=W,g,f=_0)=>{J.assertCurrent();let x=await Z.command(j,_,{cwd:P,env:G,input:g,maxBuffer:f,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)O("local_device_gh_command_failed");return x.stdout},Y=async(j)=>(await F(V,j)).toString("utf8").trim(),N=async(j,_="application/vnd.github+json")=>{U4(Q.repoFullName,j,{headers:{accept:_}}),J.assertCurrent();let P=await Z.command(V,["api","--hostname","github.com","--method","GET","--include","-H",`Accept: ${_}`,j],{cwd:W,env:G,maxBuffer:_0,timeout:Math.max(1,Math.min(25000,(J.deadlineMs??Date.now()+25000)-Date.now())),signal:J.signal});if(J.assertCurrent(),P.error&&P.status===null)O("local_device_gh_response_unavailable");let g=P.stdout.toString("utf8").match(/^HTTP\/[^ ]+ ([0-9]{3})[^\r\n]*\r?\n([\s\S]*?)\r?\n\r?\n([\s\S]*)$/);if(!g)O("local_device_gh_response_invalid");let f=Number(g[1]);if(f>=200&&f<300&&P.status!==0)O("local_device_gh_response_unavailable");if(Buffer.byteLength(g[3])>W2)O("local_device_gh_response_too_large");let x={};for(let r of g[2].split(/\r?\n/)){let o=r.indexOf(":"),w0=r.slice(0,o).toLowerCase();if(["link","content-type"].includes(w0))x[w0]=r.slice(o+1).trim().slice(0,8192)}return{kind:"read",status:f,headers:x,body:f>=200&&f<300?g[3]:JSON.stringify({message:"local_device_gh_request_failed"})}};if(Q.kind==="read")return N(Q.path,Q.accept);if(Q.kind==="pr_review_context"){let[j,_]=Q.repoFullName.split("/"),P=await Y(["api","graphql","--hostname","github.com","-f",`query=${X4}`,"-f",`owner=${j}`,"-f",`repo=${_}`,"-F",`number=${Q.number}`,...Q.after?["-f",`after=${Q.after}`]:[]]);if(Buffer.byteLength(P)>W2)O("local_device_gh_response_too_large");let g=JSON.parse(P);if(g.errors||g.data?.repository?.nameWithOwner?.toLowerCase()!==Q.repoFullName.toLowerCase()||g.data.repository.pullRequest?.number!==Q.number)O("local_device_gh_response_invalid");return{kind:"pr_review_context",body:P}}if(Q.kind==="pr_merge"){let j=await N(`/repos/${Q.repoFullName}/pulls/${Q.number}`),_=JSON.parse(j.body),P=(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(j.status!==200||!P(_)||_.state!=="open"||_.draft!==!1||_.head?.sha!==Q.expectedHeadSha||_.base?.repo?.full_name?.toLowerCase()!==Q.repoFullName.toLowerCase())O("local_device_gh_merge_target_changed");await Y(["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 g=await N(`/repos/${Q.repoFullName}/pulls/${Q.number}`),f=JSON.parse(g.body);if(g.status!==200||!P(f)||f.merged!==!0)O("local_device_gh_merge_unconfirmed");return{kind:"pr_merge",number:Q.number,merged:!0}}if(Q.kind==="pr_create"){if(Q.head===Q.base)O("local_device_gh_default_branch");let j=await Y(["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(j))O("local_device_gh_mutation_unconfirmed");return{kind:"pr_create",url:j}}if(Q.kind==="pr_mutation"){let j=Q.mutation,_=j.action==="edit"?["edit",...j.title!==void 0?[`--title=${j.title}`]:[],...j.body!==void 0?[`--body=${j.body}`]:[],...j.base?[`--base=${j.base}`]:[]]:j.action==="metadata"?["edit",`--${j.change}-${j.field}=${j.value}`]:j.action==="ready"?["ready"]:j.action==="draft"?["ready","--undo"]:["close"];return await Y(["pr",..._,String(Q.number),"--repo",Q.repoFullName]),{kind:"pr_mutation",number:Q.number,applied:!0}}if(!J.repoPath)O("local_device_gh_workspace_unavailable");let C=T.realpathSync(J.repoPath);if(!X2(B,C))O("local_device_gh_workspace_unavailable");let L=`https://github.com/${Q.repoFullName}.git`,D="!'"+(V0?V.replace(/\\/g,"/"):V).replace(/'/g,"'\\''")+"' auth git-credential",w=W4(t3),M=(j,_,P)=>process.platform==="darwin"?["/usr/bin/sandbox-exec",["-p",j,_,...P]]:[_,P],I=async(j,_,P,g=_0)=>{let f=X2(W,j),x=["-c","core.hooksPath=/dev/null","-c","core.fsmonitor=false","-c","credential.helper=","-c","http.extraheader=",...f?["-c",`credential.https://github.com.helper=${D}`]:[],"-c","protocol.ext.allow=never","-c","protocol.file.allow=never","-c","protocol.ssh.allow=never",..._];if(f)return F(z,x,j,P,g);let r=b.join(C,".ara-local-gh-tmp");if(T.mkdirSync(r,{recursive:!0,mode:448}),T.lstatSync(r).isSymbolicLink()||T.realpathSync(r)!==r)O("local_device_gh_workspace_unavailable");J.assertCurrent();let o=await Z.command(...M(w(C,r),z,x),{cwd:j,input:P,maxBuffer:g,timeout:Math.max(1,Math.min(25000,(J.deadlineMs??Date.now()+25000)-Date.now())),signal:J.signal,env:{...L1,PATH:s0,HOME:C,TMPDIR:r,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(),o.error||o.status!==0)O("local_device_gh_collection_failed");return o.stdout},A=async(j,_)=>(await I(j,_)).toString("utf8").trim(),S=async(j,_)=>{let P=b.join(j,".ara-local-gh-tmp");if(T.mkdirSync(P,{recursive:!0,mode:448}),T.lstatSync(P).isSymbolicLink()||T.realpathSync(P)!==P)O("local_device_gh_workspace_unavailable");J.assertCurrent();let g=await Z.command(...M(w(j,P),B9(z),["-c",'printf "%s\\n" "$1" > .git/shallow',"sh",_]),{cwd:j,maxBuffer:65536,timeout:Math.max(1,Math.min(25000,(J.deadlineMs??Date.now()+25000)-Date.now())),signal:J.signal,env:{...L1,PATH:s0,HOME:j,TMPDIR:P}});if(J.assertCurrent(),g.error||g.status!==0)O("local_device_gh_materialization_failed")},v=async(j)=>{let _=new Map;if(j.length===0)return _;let P=await I(m,["cat-file","--batch"],[...new Set(j)].join(`
14
+ `)+`
15
+ `,_0*8);for(let g=0;g<P.length;){let f=P.indexOf(10,g),[x,r,o]=P.subarray(g,f).toString("utf8").split(" ");if(f<0||!x||r!=="blob"||!/^[0-9]+$/.test(o??""))O("local_device_gh_object_invalid");_.set(x,P.subarray(f+1,f+1+Number(o)).toString("utf8")),g=f+1+Number(o)+1}return _},s=async(j,_,P)=>{let g=b.join(C,".ara-local-gh-tmp"),f=w(C,g)+`
16
+ (allow file-read* file-write* (subpath ${JSON.stringify(C)}))
17
+ (allow file-read* (subpath ${JSON.stringify(j)}))
18
+ (allow file-read-metadata (path-ancestors ${JSON.stringify(j)}))`,x=async(o,w0)=>{J.assertCurrent();let u0=await Z.command(...M(f,o,w0),{cwd:C,maxBuffer:_0,timeout:Math.max(1,Math.min(25000,(J.deadlineMs??Date.now()+25000)-Date.now())),signal:J.signal,env:{...L1,PATH:s0,HOME:C,TMPDIR:g,GIT_INDEX_FILE:b.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(),u0.error||u0.status!==0)O("local_device_gh_materialization_failed")},r=["--git-dir="+j,"--work-tree="+C,"-c","core.hooksPath=/dev/null","-c","core.fsmonitor=false","-c","credential.helper=","-c","http.extraheader=","-c","protocol.allow=never"];await x(z,[...r,"read-tree",_]),await x(z,[...r,"checkout-index","--all","--index"]),await I(C,["update-ref","refs/heads/"+P,_]),await I(C,["symbolic-ref","HEAD","refs/heads/"+P])};K="local_device_gh_prepare_metadata";let z0=await N(`/repos/${Q.repoFullName}`);if(z0.status!==200)O("local_device_gh_repository_unavailable");let C0=JSON.parse(z0.body);if(C0.full_name?.toLowerCase()!==Q.repoFullName.toLowerCase()||C0.default_branch!==Q.defaultBranch||Q.kind==="publish"&&C0.permissions?.push!==!0)O("local_device_gh_repository_authority_changed");if(Q.branch===Q.defaultBranch)O("local_device_gh_default_branch");K="local_device_gh_prepare_private_init";let m=T.mkdtempSync(b.join(W,"github-publication-"));T.chmodSync(m,448);let z1=!1;try{if(await I(m,["init","--bare","--template="]),Q.kind==="prepare"){if(K="local_device_gh_prepare_fetch",await I(m,["fetch","--depth=1","--no-tags","--no-recurse-submodules",L,Q.baseSha]),await A(m,["rev-parse","FETCH_HEAD"])!==Q.baseSha)K="local_device_gh_prepare_base_mismatch",O("local_device_gh_base_changed");K="local_device_gh_prepare_checkout_validation";let u=b.join(C,".git"),Q0=!1;if(T.existsSync(u)){if(!T.lstatSync(u).isDirectory()||T.lstatSync(u).isSymbolicLink()||["objects/info/alternates","info/grafts"].some((c)=>T.existsSync(b.join(u,c))))O("local_device_gh_repository_layout_invalid");let i=await I(C,["rev-parse","--verify","-q","HEAD"]).then((c)=>c.toString("utf8").trim(),()=>null),K0=await I(C,["config","--local","--get","remote.origin.url"]).then((c)=>c.toString("utf8").trim(),()=>"");if(i!==null||K0){if(i!==Q.baseSha||await A(C,["branch","--show-current"])!==Q.branch)O("local_device_gh_checkout_exists");return{kind:"prepare",headSha:Q.baseSha}}Q0=!0}let t=T.readdirSync(C).filter((i)=>!(Q0&&i===".git")),U0=[".ara-local-gh-tmp",".reason-local-gh-tmp"];if(t.some((i)=>!U0.includes(i))||t.some((i)=>{let K0=b.join(C,i);return!T.lstatSync(K0).isDirectory()||T.lstatSync(K0).isSymbolicLink()||T.readdirSync(K0).length>0}))O("local_device_gh_checkout_not_empty");if(K="local_device_gh_prepare_checkout_init",!Q0)await I(C,["init","--template="]);K="local_device_gh_prepare_materialization";let F0=await I(m,["pack-objects","--stdout","--revs"],Q.baseSha+`
19
+ `,V4);return await S(C,Q.baseSha),await I(C,["index-pack","--strict","--stdin"],F0,65536),await I(C,["remote","add","origin",L]),await s(m,Q.baseSha,Q.branch),{kind:"prepare",headSha:Q.baseSha}}let j=b.join(C,".git");if(!T.lstatSync(j).isDirectory()||T.lstatSync(j).isSymbolicLink()||["objects/info/alternates","info/grafts"].some((u)=>T.existsSync(b.join(j,u))))O("local_device_gh_repository_layout_invalid");if(await A(C,["branch","--show-current"])!==Q.branch)O("local_device_gh_branch_changed");let _=await A(C,["rev-parse","--verify","HEAD"]);if(!U2.test(_))O("local_device_gh_head_invalid");let P=await N(`/repos/${Q.repoFullName}/commits/${Q.baseSha}`);if(P.status!==200||JSON.parse(P.body).sha!==Q.baseSha)O("local_device_gh_base_unverified");let g=await N(`/repos/${Q.repoFullName}/git/ref/heads/${encodeURIComponent(Q.branch)}`);if(Q.remoteHeadSha===null?g.status!==404:g.status!==200||JSON.parse(g.body).object?.sha!==Q.remoteHeadSha)O("local_device_gh_remote_changed");let f=[...(await A(C,["rev-list","--objects","--no-object-names",_,"--not",Q.baseSha])).split(`
20
+ `),...(await A(C,["rev-list","--objects","--no-object-names","--no-walk",Q.baseSha])).split(`
21
+ `)].filter(Boolean);if(f.some((u)=>!U2.test(u)))O("local_device_gh_object_invalid");let x=await I(C,["pack-objects","--stdout"],[...new Set(f)].join(`
22
+ `)+`
23
+ `,V4);if(T.writeFileSync(b.join(m,"shallow"),Q.baseSha+`
24
+ `,{flag:"wx",mode:384}),await I(m,["index-pack","--strict","--stdin"],x,65536),await I(m,["merge-base","--is-ancestor",Q.baseSha,_]),Q.remoteHeadSha)await I(m,["merge-base","--is-ancestor",Q.remoteHeadSha,_]);let r=await I(m,["show","-s","--format=%B",_]),o=(await I(m,["interpret-trailers","--parse"],r)).toString("utf8"),w0=Q.contributorTrailers?{expectedTrailers:Q.contributorTrailers,missingFromHead:U9(o,Q.contributorTrailers)}:void 0,u0=(await A(m,["rev-list","--objects","--no-object-names",_,"--not",Q.baseSha,...Q.remoteHeadSha?[Q.remoteHeadSha]:[]])).split(`
25
+ `).filter(Boolean);if(u0.length>5000)O("local_device_gh_collection_too_large");let p0=[],h3=0;for(let u of u0){if(!U2.test(u))O("local_device_gh_object_invalid");let Q0=await A(m,["cat-file","-t",u]);if(!["blob","commit","tree"].includes(Q0))O("local_device_gh_object_invalid");let t=await I(m,["cat-file",Q0,u]);if(h3+=t.length,h3>_0)O("local_device_gh_collection_too_large");if(Q0==="tree"){let U0=0;while(U0<t.length){let F0=t.indexOf(32,U0),i=t.indexOf(0,F0+1);if(F0<U0||i<=F0||i+21>t.length)O("local_device_gh_object_invalid");let K0=t.subarray(F0+1,i).toString("utf8");if(K0.includes("/")||!G2(K0).valid)O("local_device_gh_object_invalid");U0=i+21}}p0.push({path:`object-${u}`,content:t.toString("utf8")})}let m3=J.secretNames?{secretNames:J.secretNames}:{},d0=M1(p0,J.forbiddenSecretValues,m3),v3=new Map;if(!d0.clean)try{let u=(await I(m,["diff","--no-renames","--no-abbrev","--raw","-z",Q.baseSha,_])).toString("utf8").split("\x00"),Q0=[],t=[];for(let c=0;c+1<u.length;c+=2){let[,y7,h7,Z2,F1]=u[c].slice(1).match(/^([0-7]{6}) ([0-7]{6}) ([0-9a-f]{40}) ([0-9a-f]{40}) /)??[];if(!Z2||!F1)continue;if(y7!=="160000"&&!/^0+$/.test(Z2))Q0.push(Z2);if(h7!=="160000"&&!/^0+$/.test(F1))t.push(F1),v3.set(`object-${F1}`,u[c+1])}let U0=await v([...Q0,...t]),F0=new Set(d0.violations.map((c)=>c.path)),i=K4(p0.filter((c)=>F0.has(c.path)),J.forbiddenSecretValues),K0=B4(i,t.map((c)=>U0.get(c)??""),Q0.map((c)=>U0.get(c)??""));if(K0.size>0)d0=M1(p0,J.forbiddenSecretValues,{...m3,published:K0})}catch{}if(!d0.clean)G4(d0.violations,(u)=>v3.get(u)??`an object in the pushed history (${u})`,"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 I(m,["push","--no-recurse-submodules",L,`${_}:refs/heads/${Q.branch}`]);let u3=await N(`/repos/${Q.repoFullName}/git/ref/heads/${encodeURIComponent(Q.branch)}`);if(u3.status!==200||JSON.parse(u3.body).object?.sha!==_)O("local_device_gh_push_unconfirmed");return{kind:"publish",headSha:_,scannedObjectCount:p0.length,...w0?{attribution:w0}:{}}}catch(j){throw z1=!0,j}finally{try{T.rmSync(m,{recursive:!0,force:!0})}catch(j){if(!z1||Q.kind!=="prepare")throw K=null,j}}}catch(B){if(Q.kind==="prepare"&&Q.diagnosticsVersion===1&&K&&!J.signal?.aborted)throw new O1(K);throw B}}var P0=X.object({profile:X.string().regex(/^(Default|Profile [0-9]+)$/),extension_instance_id:X.string().min(1).max(1024)}).strict(),z2={ready:X.literal(!0),boot_generation:X.string().uuid(),proof_ready:X.literal(!1),result:X.literal("metadata_only")},z9=X.object({...z2,version:X.literal(2),development_only:X.literal(!1),image:X.literal(!0),video:X.literal(!1),source_bound:X.literal(!1),profiles:X.array(P0.shape.profile).min(1).max(16),extension_instance_ids:X.array(P0.shape.extension_instance_id.max(512)).min(1).max(16)}).strict().refine(($)=>new Set($.profiles).size===$.profiles.length&&$.profiles.length===$.extension_instance_ids.length),F9=X.object({...z2,version:X.literal(3),development_only:X.literal(!1),image:X.literal(!0),video:X.literal(!0),source_bound:X.literal(!1),max_seconds:X.literal(15),profiles:X.array(P0.shape.profile).min(1).max(16),extension_instance_ids:X.array(P0.shape.extension_instance_id.max(512)).min(1).max(16)}).strict().refine(($)=>new Set($.profiles).size===$.profiles.length&&$.profiles.length===$.extension_instance_ids.length),F2=X.union([z9,F9]),iQ=X.union([X.object({...z2,version:X.literal(1),development_only:X.literal(!0),profile:P0.shape.profile,extension_instance_id:P0.shape.extension_instance_id,max_seconds:X.literal(15)}).strict(),F2]);import{createServer as Y9,request as N9}from"http";import{connect as H9,isIP as C9}from"net";var D4=120000,w9=15000;function D9($,J,Z){let Q=H4(J).toLowerCase().replace(/\.$/,"");if(!Q||C9(Q))return!1;return $.some((K)=>{if(!w4.test(K))return!1;let B=K.lastIndexOf(":"),V=B>0?K.slice(0,B):K;if(B>0&&Number(K.slice(B+1))!==Z)return!1;return V.startsWith("*.")?Q.endsWith(V.slice(1)):Q===V})}function j9($,J){let Z=/^\[?([^\]]+?)\]?:([0-9]{1,5})$/.exec($),Q=Z?Z[1]:$,K=Z?Number(Z[2]):J;return Q&&K>=1&&K<=65535?{host:Q,port:K}:null}async function Y2($,J,Z){if(!D9(Z,$,J))return null;let Q=await C4($);return Q.ok?Q.addresses[0]:null}function n0($,J){$.end(`HTTP/1.1 ${J} ${J===403?"Forbidden":"Bad Gateway"}\r
26
+ Connection: close\r
27
+ Content-Length: 0\r
28
+ \r
29
+ `)}function F4($,J){return new Promise((Z,Q)=>{let K=H9({host:$,port:J}),B=setTimeout(()=>K.destroy(Error("connect_timeout")),w9);K.once("connect",()=>{clearTimeout(B),Z(K)}),K.once("error",(V)=>{clearTimeout(B),Q(V)})})}function Y4($,J,Z){for(let Q of[$,J])Q.on("error",()=>{$.destroy(),J.destroy()}),Q.on("close",()=>{$.destroy(),J.destroy()});if(J.setTimeout(D4,()=>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 j4($,J=()=>{}){let Z=[...$],Q=new Set,K=(U)=>{Q.add(U),U.once("close",()=>Q.delete(U))},B=Y9((U,z)=>{(async()=>{let W;try{W=new URL(U.url??"")}catch{W=new URL("invalid:")}let G=Number(W.port||80),F=W.protocol==="http:"?await Y2(W.hostname,G,Z):null;if(!F){J(),z.writeHead(403,{connection:"close"}).end();return}let Y=N9({host:F,port:G,method:U.method,path:`${W.pathname}${W.search}`,headers:N4(U.headers,W.host),agent:!1,timeout:D4},(N)=>{z.writeHead(N.statusCode??502,N.headers),N.pipe(z)});Y.on("timeout",()=>Y.destroy()),Y.on("error",()=>{if(!z.headersSent)z.writeHead(502);z.end()}),z.on("close",()=>Y.destroy()),U.pipe(Y)})().catch(()=>{if(!z.headersSent)z.writeHead(502);z.end()})});B.on("connection",K),B.on("connect",(U,z,W)=>{K(z),z.on("error",()=>z.destroy()),(async()=>{let G=j9(U.url??"",443),F=G?await Y2(G.host,G.port,Z):null;if(!G||!F){J(),n0(z,403);return}let Y=await F4(F,G.port).catch(()=>null);if(!Y){n0(z,502);return}if(z.destroyed){Y.destroy();return}K(Y),z.write(`HTTP/1.1 200 Connection Established\r
30
+ \r
31
+ `),Y4(z,Y,W)})().catch(()=>z.destroy())}),B.on("upgrade",(U,z,W)=>{K(z),z.on("error",()=>z.destroy()),(async()=>{let G;try{G=new URL(U.url??"")}catch{n0(z,403);return}let F=Number(G.port||80),Y=["http:","ws:"].includes(G.protocol)?await Y2(G.hostname,F,Z):null;if(!Y){J(),n0(z,403);return}let N=await F4(Y,F).catch(()=>null);if(!N){n0(z,502);return}K(N);let C=N4(U.headers,G.host),L=[`${U.method} ${G.pathname}${G.search} HTTP/1.1`];for(let[D,w]of Object.entries(C))for(let M of Array.isArray(w)?w:w===void 0?[]:[w])L.push(`${D}: ${M}`);N.write(`${L.join(`\r
32
+ `)}\r
33
+ \r
34
+ `),Y4(z,N,W)})().catch(()=>z.destroy())}),await new Promise((U,z)=>{B.once("error",z),B.listen(0,"127.0.0.1",()=>U())});let{port:V}=B.address();return{url:`http://127.0.0.1:${V}`,close(){B.close();for(let U of Q)U.destroy()}}}import{createHash as O2,randomUUID as O9}from"crypto";import{closeSync as g1,constants as e,fchownSync as A9,fstatSync as j0,fsyncSync as _9,linkSync as E4,lstatSync as j2,mkdirSync as k4,openSync as R1,readSync as x4,realpathSync as M2,unlinkSync as S4,writeSync as P9}from"fs";import{isAbsolute as T9,join as R9,relative as q9,sep as g9}from"path";import{platform as L2}from"os";import{getSystemErrorName as E9}from"util";var M4={type:"string",format:"uuid"},A4=String.raw`^(?![\\/])(?![A-Za-z]:[\\/])(?!.*(?:^|[\\/])\.\.(?:[\\/]|$))(?!.*\u0000)(?=.*\S)[\s\S]+$`,A1={type:"string",minLength:1,maxLength:4096,pattern:A4},N2=X.string().min(1).max(4096).regex(new RegExp(A4)),_1={device_id:X.string().uuid(),root_id:X.string().uuid(),timeout_ms:X.number().int().min(1000).max(60000).optional()},P1={device_id:M4,root_id:M4,timeout_ms:{type:"integer",minimum:1000,maximum:60000}},KK={read:{schema:X.object({..._1,path:N2,offset:X.number().int().min(0).optional(),max_bytes:X.number().int().min(1).max(131072).optional()}).strict(),inputSchema:{type:"object",required:["device_id","root_id","path"],properties:{...P1,path:A1,offset:{type:"integer",minimum:0},max_bytes:{type:"integer",minimum:1,maximum:131072}},additionalProperties:!1}},write:{schema:X.object({..._1,path:N2,content:X.string().max(131072),mode:X.enum(["overwrite","append"]).optional(),create_parents:X.boolean().optional()}).strict(),inputSchema:{type:"object",required:["device_id","root_id","path","content"],properties:{...P1,path:A1,content:{type:"string",maxLength:131072},mode:{type:"string",enum:["overwrite","append"]},create_parents:{type:"boolean"}},additionalProperties:!1}},exec:{schema:X.object({..._1,command:X.string().min(1).max(16000),cwd:N2.optional(),mode:X.enum(["confined","host"]).optional()}).strict(),inputSchema:{type:"object",required:["device_id","root_id","command"],properties:{...P1,command:{type:"string",minLength:1,maxLength:16000},cwd:A1,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}}},X0=1073741824,r0=600000,L4=String.raw`(?!\.{1,2}(?:/|(?![\s\S])))[^/\\\u0000]+`,_4=String.raw`^(?![A-Za-z]:/)(?=[\s\S]*\S)${L4}(?:/${L4})*(?![\s\S])`,P4=new RegExp(_4);function T4($){return typeof $==="string"&&$.length>0&&$.length<=4096&&P4.test($)}var H2=X.string().min(1).max(4096).regex(P4),C2={...A1,pattern:_4},R4=X.string().regex(/^[a-f0-9]{64}$/),q4=X.object({kind:X.literal("workspace"),path:H2}).strict(),M9=X.discriminatedUnion("kind",[q4,X.object({kind:X.literal("attachment"),attachment_id:X.string().min(1).max(120),sha256:R4}).strict()]),T1=1,a0="cloud_workspace_id",w2="cloud_workspace",D2=1,L9=X.discriminatedUnion("kind",[q4,X.object({kind:X.literal("attachment"),download_url:X.string().min(1).max(16384),size_bytes:X.number().int().min(0).max(X0),sha256:R4}).strict()]),g4=X.object({source_version:X.literal(T1),source:L9,url:X.string().min(1).max(16384),transfer_cloud_scope:X.object({sandboxId:X.string().min(1).max(256),revision:X.number().int().nonnegative(),brainFence:X.string().uuid()}).strict().optional(),[a0]:X.string().min(1).max(160).optional()}).strict(),BK=X.object({ready:X.literal(!0),cloud_source_version:X.literal(T1),source_kinds:X.array(X.enum(["workspace","attachment"]))});var I4=X.object({..._1,timeout_ms:X.number().int().min(1000).max(r0).optional(),source_path:H2,destination_path:H2,idempotency_key:X.string().min(1).max(160).regex(/^[A-Za-z0-9._:-]+$/).optional()}).strict(),O4={type:"object",required:["device_id","root_id","source_path","destination_path"],properties:{...P1,timeout_ms:{type:"integer",minimum:1000,maximum:r0},source_path:C2,destination_path:C2,idempotency_key:{type:"string",minLength:1,maxLength:160,pattern:"^[A-Za-z0-9._:-]+$"}},additionalProperties:!1},I9={oneOf:[{type:"object",required:["kind","path"],properties:{kind:{type:"string",const:"workspace"},path:C2},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}]},VK=X.union([I4,I4.omit({source_path:!0}).extend({source:M9}).strict()]),GK={...O4,required:["device_id","root_id","destination_path"],properties:{...O4.properties,source:I9},oneOf:[{required:["source_path"],not:{required:["source"]}},{required:["source"],not:{required:["source_path"]}}]};var A2=65536;function p($){throw new H($,$)}function E1($){return typeof $==="object"&&$!==null&&"code"in $&&typeof $.code==="string"?$.code:void 0}function q1($,J,Z){if(J.throwIfAborted(),$ instanceof H||$ instanceof Error&&$.name==="AbortError")throw $;return p(Z)}function k9($,J,Z){let Q;switch(E1($)){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 q1($,J,Q)}function S9($){if(typeof $!=="string"||$.length>16384)return p("transfer_url_invalid");let J;try{J=new URL($)}catch{return p("transfer_url_invalid")}if(J.protocol!=="https:"||J.username||J.password||J.hash)return p("transfer_url_invalid");return J.href}var I2=e.O_RDONLY|e.O_DIRECTORY|e.O_NOFOLLOW;async function b9(){if(L2()==="win32"){let W=new Map,G,F=-1,Y=()=>Object.assign(Error("transfer_path_unsafe"),{code:"ELOOP"}),N=(w)=>{let M=q9(G,w);return M===""||M!==".."&&!M.startsWith(`..${g9}`)&&!T9(M)},C=(w)=>{let M=j2(w);if(M.isSymbolicLink())throw Y();if(!M.isDirectory())throw Object.assign(Error("transfer_path_unsafe"),{code:"ENOTDIR"});let I=M2(w);if(G??=I,!N(I))throw Y();return W.set(F,{path:w,real:I}),F--},L=(w)=>{let M=W.get(w);if(M2(M.path)!==M.real)throw Y();return M.path},D=(w,M)=>{if(k1(M))throw Object.assign(Error("transfer_path_invalid"),{code:"ENOTDIR"});return R9(W.get(w).path,M)};return{root:C,openDirectory:(w,M)=>C(D(w,M)),open:(w,M,I,A=384)=>{let S=D(w,M);if(j2(S,{throwIfNoEntry:!1})?.isSymbolicLink())throw Y();L(w);let v=R1(S,I,A);try{let s=j0(v),z0=j2(S);if(z0.isSymbolicLink()||s.ino!==z0.ino||s.dev!==z0.dev||!N(M2(S)))throw Y()}catch(s){throw g1(v),s}return v},mkdir:(w,M)=>{let I=D(w,M);L(w),k4(I)},link:(w,M,I)=>{let A=D(w,M),S=D(w,I);L(w),E4(A,S)},unlink:(w,M)=>S4(D(w,M)),closeDirectory:(w)=>{W.delete(w)},inherit:()=>{},close:()=>{}}}let $={root:(W)=>R1(W,I2),closeDirectory:g1,inherit:f9};if(L2()==="linux")return{...$,openDirectory:(W,G)=>R1(`/proc/self/fd/${W}/${G}`,I2),open:(W,G,F,Y=384)=>R1(`/proc/self/fd/${W}/${G}`,F,Y),mkdir:(W,G)=>k4(`/proc/self/fd/${W}/${G}`,{mode:448}),link:(W,G,F)=>E4(`/proc/self/fd/${W}/${G}`,`/proc/self/fd/${W}/${F}`),unlink:(W,G)=>S4(`/proc/self/fd/${W}/${G}`),close:()=>{}};if(L2()!=="darwin")return p("transfer_platform_unsupported");let{dlopen:J,FFIType:Z,ptr:Q,read:K}=await import("bun:ffi"),B=J("/usr/lib/libSystem.B.dylib",{__error:{args:[],returns:Z.ptr},openat:{args:[Z.i32,Z.ptr,Z.i32,Z.i32,Z.i32,Z.i32,Z.i32,Z.i32,Z.i32],returns:Z.i32},mkdirat:{args:[Z.i32,Z.ptr,Z.i32],returns:Z.i32},linkat:{args:[Z.i32,Z.ptr,Z.i32,Z.ptr,Z.i32],returns:Z.i32},unlinkat:{args:[Z.i32,Z.ptr,Z.i32],returns:Z.i32}}),V=B.symbols.__error();if(V===null)return B.close(),p("transfer_path_unavailable");let U=(W)=>{if(W<0){let G=E9(-K.i32(V));throw Object.assign(Error("transfer_path_unavailable"),{code:G})}return W},z=(W,G,F,Y=384)=>U(B.symbols.openat(W,Q(Buffer.from(`${G}\x00`)),F,Y,0,0,0,0,Y));return{...$,openDirectory:(W,G)=>z(W,G,I2),open:z,mkdir:(W,G)=>{U(B.symbols.mkdirat(W,Q(Buffer.from(`${G}\x00`)),448))},link:(W,G,F)=>{U(B.symbols.linkat(W,Q(Buffer.from(`${G}\x00`)),W,Q(Buffer.from(`${F}\x00`)),0))},unlink:(W,G)=>{U(B.symbols.unlinkat(W,Q(Buffer.from(`${G}\x00`)),0))},close:()=>B.close()}}function f9($,J){let Z=j0($),Q=j0(J);if(Q.uid!==Z.uid||Q.gid!==Z.gid)A9(J,Z.uid,Z.gid)}function x9($,J,Z,Q){if(!T4(Z))return p("transfer_path_invalid");let K=Z.split("/"),B=$.root(J);try{for(let V of K.slice(0,-1)){let U;try{U=$.openDirectory(B,V)}catch(z){if(!Q||E1(z)!=="ENOENT")throw z;try{$.mkdir(B,V)}catch(W){if(E1(W)!=="EEXIST")throw W}U=$.openDirectory(B,V),$.inherit(B,U)}$.closeDirectory(B),B=U}return{fd:B,leaf:K.at(-1)}}catch(V){throw $.closeDirectory(B),V}}function b4($,J){let Z=j0($,{bigint:!0});if(!Z.isFile()||Z.size>X0)return p("transfer_file_invalid");let Q=O2("sha256"),K=Buffer.alloc(A2),B=0;while(!0){J.throwIfAborted();let U=x4($,K,0,K.length,B);if(!U)break;if(B+=U,B>X0)return p("transfer_size_exceeded");Q.update(K.subarray(0,U))}let V=j0($,{bigint:!0});if(BigInt(B)!==Z.size||V.size!==Z.size||V.mtimeNs!==Z.mtimeNs||V.ctimeNs!==Z.ctimeNs)return p("transfer_source_changed");return{size_bytes:B,sha256:Q.digest("hex")}}async function T0($){$.signal.throwIfAborted();try{let J=S9($.payload.url),Z=await b9(),Q,K,B;try{if(Q=x9(Z,$.root,$.path,$.direction==="import"),$.direction==="export"){K=Z.open(Q.fd,Q.leaf,e.O_RDONLY|e.O_NOFOLLOW|e.O_NONBLOCK);let Y=j0(K,{bigint:!0});if(!Y.isFile()||Y.size>X0)return p("transfer_file_invalid");let N=O2("sha256"),C=0,L=K,D,w=new ReadableStream({pull(S){try{$.signal.throwIfAborted();let v=Buffer.alloc(A2),s=x4(L,v,0,v.length,C);if(!s){S.close();return}if(C+=s,C>Y.size)return p("transfer_source_changed");N.update(v.subarray(0,s)),S.enqueue(v.subarray(0,s))}catch(v){throw D=v,v}}});try{let S=await($.fetchImpl??fetch)(J,Object.assign({method:"PUT",body:w,redirect:"error",signal:$.signal,headers:{"content-type":"application/octet-stream","content-length":String(Y.size)}},{duplex:"half"}));if(D!==void 0)throw D;if(!S.ok)return p("transfer_upload_failed");await S.body?.cancel()}catch(S){if(D!==void 0)throw D;return q1(S,$.signal,"transfer_upload_failed")}let M=j0(K,{bigint:!0});if(BigInt(C)!==Y.size||M.size!==Y.size||M.mtimeNs!==Y.mtimeNs||M.ctimeNs!==Y.ctimeNs)return p("transfer_source_changed");let I=N.digest("hex"),A=b4(K,$.signal);if(A.size_bytes!==C||A.sha256!==I)return p("transfer_source_changed");return{size_bytes:C,sha256:I,outcome:"copied"}}let V=$.payload.size_bytes,U=$.payload.sha256;if(typeof V!=="number"||!Number.isSafeInteger(V)||V<0||V>X0||typeof U!=="string"||!/^[a-f0-9]{64}$/.test(U))return p("transfer_receipt_invalid");let z;try{z=Z.open(Q.fd,Q.leaf,e.O_RDONLY|e.O_NOFOLLOW|e.O_NONBLOCK)}catch(Y){if(E1(Y)!=="ENOENT")throw Y}if(z!==void 0){try{let Y=b4(z,$.signal);if(Y.size_bytes===V&&Y.sha256===U)return{...Y,outcome:"already_present"}}finally{g1(z)}return p("transfer_destination_exists")}B=`.reason-copy-${O9()}`,K=Z.open(Q.fd,B,e.O_CREAT|e.O_EXCL|e.O_WRONLY|e.O_NOFOLLOW,384),Z.inherit(Q.fd,K);let W;try{let Y=await($.fetchImpl??fetch)(J,{redirect:"error",signal:$.signal});if(!Y.ok||!Y.body)return p("transfer_download_failed");W=Y.body.getReader()}catch(Y){return q1(Y,$.signal,"transfer_download_failed")}let G=O2("sha256"),F=0;try{while(!0){$.signal.throwIfAborted();let Y=await W.read().catch((N)=>q1(N,$.signal,"transfer_download_failed"));if(Y.done)break;if(F+=Y.value.length,F>V)return p("transfer_size_mismatch");G.update(Y.value);for(let N=0;N<Y.value.length;)$.signal.throwIfAborted(),N+=P9(K,Y.value,N,Math.min(A2,Y.value.length-N))}}finally{await W.cancel().catch(()=>{})}if(F!==V||G.digest("hex")!==U)return p("transfer_hash_mismatch");return _9(K),await $.beforeCommit?.(),$.signal.throwIfAborted(),Z.link(Q.fd,B,Q.leaf),{size_bytes:V,sha256:U,outcome:"copied"}}finally{try{if(K!==void 0)g1(K)}finally{try{if(Q){if(B)try{Z.unlink(Q.fd,B)}catch{}Z.closeDirectory(Q.fd)}}finally{Z.close()}}}}catch(J){return k9(J,$.signal,$.direction)}}import{spawn as h9}from"child_process";import{mkdtempSync as m9,rmSync as v9,writeFileSync as u9}from"fs";import{constants as p9,platform as d9,tmpdir as l9}from"os";import{join as v4}from"path";import{gunzipSync as y9,gzipSync as jK}from"zlib";var h4=900000,LK=h4+60000,i0=49152,y4=($)=>X.string().min(1).max($).regex(/^[A-Za-z0-9+/]+=*$/),m4=X.object({version:X.literal(1),script_gzip:y4(163840),stdin_gzip:y4(65536),cwd:X.string().min(1).max(4096).startsWith("/"),env:X.record(X.string().regex(/^[A-Z_][A-Z0-9_]{0,63}$/),X.string().max(4096)).refine(($)=>Object.keys($).length<=16,"too many variables"),timeout_ms:X.number().int().min(1000).max(h4)}).strict(),_2=X.string().max(i0+256),IK=X.object({exit_code:X.number().int().min(0).max(255),stdout:_2,stderr:_2,combined:_2.optional()}).strict();function P2($){return y9(Buffer.from($,"base64")).toString("utf8")}var s9="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",c9=["RUSTUP_HOME","TZ","LC_ALL"],n9=2000,r9=100;function R2(){return d9()==="linux"&&process.geteuid?.()===0}function T2($){let J=Math.floor($/2),Z=[],Q=0,K=Buffer.alloc(0),B=0;return{push(V){B+=V.length;let U=V;if(Q<J){let z=U.subarray(0,J-Q);Z.push(z),Q+=z.length,U=U.subarray(z.length)}if(U.length)K=Buffer.concat([K,U]).subarray(-J)},text(){let V=B-Q-K.length;return Buffer.concat(Z).toString("utf8")+(V>0?`
35
+ [reason: ${V} bytes of output omitted]
36
+ `:"")+K.toString("utf8")}}}async function u4($,J){if(!R2())throw new H("workspace_setup_requires_root","Workspace setup runs only on a root Linux worker.");let Z=m4.safeParse($);if(!Z.success)throw new H("invalid_request","Reason sent an invalid workspace setup.");let Q=Z.data,K,B;try{K=P2(Q.script_gzip),B=P2(Q.stdin_gzip)}catch{throw new H("invalid_request","Reason sent an unreadable workspace setup.")}J.throwIfAborted();let V=m9(v4(l9(),"reason-workspace-setup-"));try{let U=v4(V,"setup.sh");u9(U,K,{mode:384});let z={PATH:s9,LANG:"C.UTF-8",HOME:"/root",USER:"root",LOGNAME:"root",SHELL:"/bin/bash",TMPDIR:"/tmp"};for(let A of c9)if(process.env[A])z[A]=process.env[A];Object.assign(z,Q.env);let W=h9("/bin/bash",[U],{cwd:Q.cwd,env:z,detached:!0,stdio:["pipe","pipe","pipe"]}),G=T2(i0),F=T2(i0),Y=T2(i0);W.stdout.on("data",(A)=>{G.push(A),Y.push(A)}),W.stderr.on("data",(A)=>{F.push(A),Y.push(A)}),W.stdin.on("error",()=>{}),W.stdin.end(B);let N=(A)=>{try{if(W.pid)process.kill(-W.pid,A)}catch{}},C=!1,L,D=()=>{N("SIGTERM"),L??=setTimeout(()=>N("SIGKILL"),n9)},w=setTimeout(()=>{C=!0,D()},Q.timeout_ms);J.addEventListener("abort",D,{once:!0});let M=await new Promise((A,S)=>{W.once("error",()=>S(new H("workspace_setup_start_failed","The workspace setup did not start."))),W.once("exit",(v,s)=>A({code:v,signal:s}))}).finally(()=>{clearTimeout(w),clearTimeout(L),J.removeEventListener("abort",D)});await new Promise((A)=>{let S=setTimeout(A,r9);W.once("close",()=>{clearTimeout(S),A()})}),W.stdout.destroy(),W.stderr.destroy(),J.throwIfAborted();let I=C?124:M.signal?128+(p9.signals[M.signal]??0):M.code??1;return{exit_code:Math.min(255,I),stdout:G.text(),stderr:F.text(),...I!==0?{combined:Y.text()}:{}}}finally{v9(V,{recursive:!0,force:!0})}}import{chmodSync as a9,mkdtempSync as i9,realpathSync as s4,rmSync as o9}from"fs";import{tmpdir as t9}from"os";import{dirname as e9,join as q2,sep as $$}from"path";function g2($){return l4($,d4($)!==null).repoPath}function c4($,J){let Z;try{if(typeof J!=="string")throw Error("invalid");Z=[o0,void 0].map((K)=>e9(p4({kind:"managed",workspaceId:J,...K?{layout:K}:{}})))}catch{throw new H("cloud_copy_workspace_invalid","The Cloud copy workspace is invalid.")}let Q;for(let K of Z)try{Q=s4(q2($,K));break}catch{}if(Q===void 0)throw new H("cloud_copy_workspace_unavailable","The Session workspace is not on this computer.");if(!Q.startsWith(`${$}${$$}`))throw new H("cloud_copy_workspace_invalid","The Cloud copy workspace is outside this worker's root.");return Q}async function n4($){$.signal.throwIfAborted();let J=$.source;if(J.kind==="workspace"){let Q=g2($.runtimeRoot);if(R0(Q)||R0(q2(Q,J.path)))throw new H("protected_path","Credential and secret paths are unavailable to local tasks.");return T0({direction:"export",root:Q,path:J.path,payload:{url:$.url},signal:$.signal,fetchImpl:$.fetchImpl})}let Z=i9(q2(t9(),`reason-cloud-copy-${process.pid}-`));try{a9(Z,448);let Q=s4(Z);await T0({direction:"import",root:Q,path:"source",payload:{url:J.download_url,size_bytes:J.size_bytes,sha256:J.sha256},signal:$.signal,fetchImpl:$.fetchImpl});let K=await T0({direction:"export",root:Q,path:"source",payload:{url:$.url},signal:$.signal,fetchImpl:$.fetchImpl});if(K.size_bytes!==J.size_bytes||K.sha256!==J.sha256)throw new H("transfer_source_changed","The verified attachment changed before export.");return K}finally{o9(Z,{recursive:!0,force:!0})}}import{constants as Z0}from"fs";import{closeSync as j7,existsSync as G0,fstatSync as M7,ftruncateSync as fZ,lstatSync as _3,mkdirSync as xZ,mkdtempSync as yZ,openSync as L7,readSync as hZ,realpathSync as B0,rmSync as mZ,statSync as W1,writeSync as vZ}from"fs";import{homedir as G1,platform as R,tmpdir as uZ}from"os";import{dirname as U1,isAbsolute as pZ,join as I7,relative as P3,resolve as dZ,sep as lZ}from"path";import{spawn as sZ}from"child_process";import{createHash as B$,randomBytes as V$}from"crypto";var E2=30000,J$=1800000,Z$=5000,S1=30000,Q$=f1+15000,r4=/^\/app\/local-runtime\/operations\/[0-9a-fA-F-]{36}\/heartbeat$/,K$=[/^\/app\/local-runtime\/operations\/claim$/,r4];class k2{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 K=String(++this.nextId),B=new Promise((z)=>Q.pending.set(K,{path:$,resolve:z}));if(!this.send(Q,{t:"req",id:K,path:$,body:J}))return Q.pending.delete(K),null;let V;if(K$.some((z)=>z.test($)))V=setTimeout(()=>{if(Q.pending.has(K))this.drop(Q)},Q$);else{let z=()=>{if(!Q.pending.has(K))return;let W=this.now()-Q.lastFrameAt;if(W>=S1)this.drop(Q);else V=setTimeout(z,S1-W)};V=setTimeout(z,S1)}if(B.finally(()=>clearTimeout(V)),!Z)return await B;let U=new Promise((z,W)=>{let G=()=>{if(Q.pending.delete(K),clearTimeout(V),this.send(Q,{t:"abort",id:K}),this.now()-Q.lastFrameAt>S1)this.drop(Q);W(Z.reason)};if(Z.aborted)G();else Z.addEventListener("abort",G,{once:!0}),B.finally(()=>Z.removeEventListener("abort",G))});return await Promise.race([B,U])}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(Z$));if(this.connecting===$){this.connecting=null,this.failures+=1;let J=Math.min(J$,E2*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(b1,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()+E2;return}let Q={socket:Z,pending:new Map,maxInFlight:0,cadence:null,lastFrameAt:this.now(),dropped:!1};this.connecting=Q,Z.onmessage=(K)=>this.receive(Q,K.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[K,B]of Q.pending){if(!r4.test(B.path))continue;Q.pending.delete(K),this.send(Q,{t:"abort",id:K}),B.resolve(null)}if(Q.pending.size===0)this.drop(Q)}return}if(Z.t==="fallback"){this.retryAt=this.now()+Math.max(E2,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 b2=["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 rK($,J={}){let Z=G$($),Q=J.rootPathsSupported===!0?H1($.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((K)=>/^[a-f0-9]{64}$/.test(K))?{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 G$($){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 K=$.operation_constraints?.[Q];if(!K||typeof K!=="object"||Array.isArray(K))continue;if(!("ready"in K)||typeof K.ready!=="boolean")continue;let B={};for(let[V,U]of Object.entries(K).slice(0,32)){if(!V.length||V.length>64||["__proto__","constructor","prototype"].includes(V))continue;if(J(U)||Array.isArray(U)&&U.length<=64&&U.every(J))B[V]=U}if(Object.keys(B).length)Z[Q]=B}return Z}class W0 extends Error{status;code;retryAfter;constructor($,J,Z,Q=null){super(Z);this.status=$;this.code=J;this.retryAfter=Q;this.name="LocalRuntimeHttpError"}}class x1 extends Error{timeoutMs;constructor($){super(`Reason Device request did not answer within ${$}ms.`);this.timeoutMs=$;this.name="LocalRuntimeRequestTimeoutError"}}function U$($){return $===408||$===429||$===500||$===502||$===503||$===504}function X$($){if($ instanceof W0)return!1;if($ instanceof x1)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 W$($,J,Z=500){if(J instanceof W0&&J.retryAfter){let B=parseFloat(J.retryAfter);if(Number.isFinite(B)&&B>0)return Math.min(B*1000,1e4)}let Q=Z*2**$,K=Math.floor(Math.random()*200);return Math.min(Q+K,5000)}async function z$($,J){if(J?.aborted)throw J.reason??new DOMException("The operation was aborted.","AbortError");await new Promise((Z,Q)=>{let K=()=>{clearTimeout(B),Q(J?.reason??new DOMException("The operation was aborted.","AbortError"))},B=setTimeout(()=>{J?.removeEventListener("abort",K),Z()},$);J?.addEventListener("abort",K,{once:!0})})}function aK($){return $ instanceof W0&&$.status===401&&($.code==="device_revoked"||$.code==="invalid_device_credential")}function a4($){return Buffer.byteLength(JSON.stringify($)??"null","utf8")}function i4($){return B$("sha256").update($??"").digest("hex")}function F$($){return J8({method:$.method,pathAndQuery:$.route,timestamp:$.timestamp,nonce:$.nonce,challenge:$.challenge,bodySha256:$.bodySha256})}function o4($){return Boolean($)&&typeof $==="object"&&!Array.isArray($)}var Y$=20000,N$=1e4,t4=[2000,4000],H$=30000,C$=15000;function e4($){return $?{keepalive:!1}:{}}class S2 extends Error{constructor($){super(`Reason Device proof challenge did not answer within ${$}ms.`)}}class w${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 K=new URL($);if(K.protocol!=="https:"&&K.hostname!=="127.0.0.1"&&K.hostname!=="localhost"&&K.hostname!=="[::1]"&&K.hostname!=="::1")throw Error("Reason Device API must use HTTPS, except for localhost development.");this.apiOrigin=K.origin}async parseResponse($){if($.status===204)return null;let J=await $.json().catch(()=>({}));if(!$.ok){let{code:Z,message:Q}=Z8(J,$.status),K=$.headers?.get?.("retry-after")??null;throw new W0($.status,Z,Q,K)}return J}async challenge($,J,Z={fresh:!1}){let Q=this.proofOptions.challengeAttemptTimeoutsMs??t4;for(let K of Q)try{return await this.challengeAttempt($,J,K,Z.fresh)}catch(B){if(J?.aborted||!(B instanceof S2))throw B;Z.fresh=!0}return await this.challengeAttempt($,J,null,Z.fresh)}async challengeAttempt($,J,Z,Q=!1){let K=JSON.stringify({device_id:$}),B=Z===null?null:new AbortController,V=B&&Z!==null?setTimeout(()=>B.abort(new S2(Z)),Z):null;try{let U=await this.fetchImpl(`${this.apiOrigin}${d.authChallenge.path}`,{method:"POST",redirect:"error",headers:{accept:"application/json","content-type":"application/json"},body:K,...e4(Q),signal:B?J?AbortSignal.any([J,B.signal]):B.signal:J});return Q8(await this.parseResponse(U))}catch(U){if(!J?.aborted&&B?.signal.aborted)throw B.signal.reason;throw U}finally{if(V)clearTimeout(V)}}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>=Y$?Z:null}refillSpareChallenge($){let J=this.challengeAttempt($,void 0,t4[0]??2000).catch(()=>null);this.spareChallenge={deviceId:$,challenge:J}}async proofHeaders($,J,Z,Q,K=!1,B,V){let U=B&&Date.parse(B.expires_at)-(this.proofOptions.now??Date.now)()>=N$?B:null,z=!U&&K?await this.takeSpareChallenge(Z.deviceId):null,W=U??z??await this.challenge(Z.deviceId,Q,V);if(K)this.refillSpareChallenge(Z.deviceId);let G=i4(J),F=this.signProof("POST",$,W.challenge,G);return{"x-device-id":Z.deviceId,"x-device-timestamp":F.timestamp,"x-device-nonce":F.nonce,"x-device-challenge":W.challenge,"x-device-body-sha256":G,"x-device-signature":F.signature}}signProof($,J,Z,Q){let K=String(Math.trunc((this.proofOptions.now??Date.now)())),B=(this.proofOptions.nonce??(()=>V$(24)))();if(B.byteLength<16||B.byteLength>32)throw Error("Invalid Reason Device proof nonce.");let V=Buffer.from(B).toString("base64url"),U=this.proofStore.sign(F$({method:$,route:J,timestamp:K,nonce:V,challenge:Z,bodySha256:Q}));if(!/^[A-Za-z0-9_-]{8,128}$/.test(U))throw Error("Reason Device proof boundary returned an invalid signature.");return{timestamp:K,nonce:V,signature:U}}sessionFor($,J){if(!this.proofOptions.deviceSession||this.sessionsClosed||!J||!$8($.path))return null;let Z=this.sessions.get(J.deviceId);if(!Z)Z=new k2({apiOrigin:this.apiOrigin,deviceId:J.deviceId,signHello:(Q)=>this.signProof("GET",b1,Q,i4("")),...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&&a4(J.body)>Y0)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 B=J.body===void 0?void 0:JSON.stringify(J.body),V=this.proofOptions.maxAttempts??4,U=this.proofOptions.sleep??z$,z=this.sessionFor($,J.device),W=Math.max(H$,(J.holdMs??0)+C$),G={fresh:!1},F;for(let Y=0;Y<V;Y+=1)try{let N=await z?.request($.path,J.sessionBody===void 0?B??"":JSON.stringify(J.sessionBody),J.signal)??null;if(N)return await this.parseResponse(new Response(N.status===204?null:N.body,{status:N.status,headers:N.retryAfter===null?{}:{"retry-after":N.retryAfter}}));let C=new AbortController,L=setTimeout(()=>C.abort(new x1(W)),W),D=J.signal?AbortSignal.any([J.signal,C.signal]):C.signal;try{let w=J.device===void 0?{}:await this.proofHeaders($.path,B,J.device,D,J.useSpareChallenge===!0&&Y===0,Y===0?J.issuedChallenge:void 0,G),M=await this.fetchImpl(`${this.apiOrigin}${$.path}`,{method:"POST",redirect:"error",headers:{...J.authorization===void 0?{}:{authorization:`Bearer ${J.authorization}`},...w,accept:"application/json",...J.body===void 0?{}:{"content-type":"application/json"}},body:B,...e4(G.fresh),signal:D});return await this.parseResponse(M)}catch(w){if(!J.signal?.aborted&&C.signal.aborted)throw C.signal.reason;throw w}finally{clearTimeout(L)}}catch(N){if(F=N,N instanceof x1)G.fresh=!0;if(J.signal?.aborted)throw N;let C=J.device!==void 0&&N instanceof W0&&N.status===401&&["invalid_device_proof","device_proof_replayed"].includes(N.code),L=N instanceof W0&&U$(N.status),D=X$(N),w=J.transientRetryOwner!=="caller"&&(L||D);if((C||w)&&Y+1<V){let M=C?0:W$(Y,N,this.proofOptions.retryBaseDelayMs??500);if(M>0)await U(M,J.signal);continue}throw N}throw F??Error("Reason Device request failed.")}async register($,J,Z){let Q=await this.request(d.register,{authorization:$,body:J,signal:Z});return K8(Q)}async enroll($,J,Z,Q){let K=await this.request(d.enroll,{body:{...Z,enrollment_ticket:$,code_verifier:J},signal:Q});return B8(K)}async heartbeat($,J,Z,Q){let K=await this.request(d.heartbeat,{device:$,body:J,signal:Z,...Q?{issuedChallenge:Q}:{}});return V8(K)}async syncRoots($,J,Z){let Q=await this.request(d.rootsSync,{device:$,body:{roots:J},signal:Z});return G8(Q)}async identity($,J){let Z=await this.request(d.identity,{device:$,signal:J});return U8(Z)}async disconnect($,J,Z,Q=[]){let K=await this.request(d.disconnect,{device:$,body:Z?{successor_device_id:Z,...Q.length?{successor_roots:Q}:{}}:{},signal:J});return X8(K)}async deviceLifecycle($,J,Z){let Q=await this.request(d.lifecycle,{device:$,body:J,signal:Z});z8(Q)}async localSubscription($,J,Z){return W8(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((K)=>{let B=K;return typeof B?.id==="string"?[{id:B.id,...typeof B.name==="string"&&B.name.trim()?{name:B.name.trim()}:{},blocked:B.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((K)=>{if(K instanceof W0&&K.status===404)return null;throw K});if(Q===null)return null;if(!o4(Q)||!Array.isArray(Q.live)||!Q.live.every((K)=>typeof K==="string"&&J.includes(K)))throw Error("Reason returned an invalid Session worktree answer.");return Q.live}async claimOperation($,J={}){let Z=Math.max(J.waitMs??25000,0),Q=(V)=>({wait_ms:Math.min(Z,V),...J.instanceGeneration===void 0?{}:{instance_generation:J.instanceGeneration}}),K=this.sessionCadence($)?.claimWaitMs,B=await this.request(d.operationClaim,{device:$,body:Q(30000),holdMs:Math.min(Z,30000),...K===void 0?{}:{sessionBody:Q(Math.min(K,f1))},signal:J.signal});if(B===null)return null;return F8(B,b2)}async operationHeartbeat($,J,Z={}){let Q=(V)=>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},...V?{client_retry_count:Z.clientRetryCount}:{},...V&&Z.waitMs!==void 0?{wait_ms:Math.min(Math.max(Z.waitMs,0),30000)}:{}},signal:Z.signal,transientRetryOwner:Z.transientRetryOwner,...V&&Z.waitMs!==void 0?{holdMs:Math.min(Math.max(Z.waitMs,0),30000)}:{}}),K=(Z.clientRetryCount??0)>0||Z.waitMs!==void 0,B;try{B=await Q(K)}catch(V){if(!K||!(V instanceof W0)||V.status!==400||V.code!=="invalid_operation_heartbeat")throw V;B=await Q(!1)}return Y8(B)}async operationEvents($,J,Z){if(!Number.isInteger(Z.eventSeqStart)||Z.eventSeqStart<0||Z.events.length<1||Z.events.length>100||Z.events.some((K)=>!/^[A-Za-z0-9._:-]{1,64}$/.test(K.kind)||!o4(K.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 N8(Q)}async completeOperation($,J,Z,Q){let K={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(a4(K)>Y0)throw Error("Reason Device operation result exceeds the 256 KB protocol limit.");let B=await this.request(d.operationComplete.forOperation(J.operation_id),{device:$,body:K,signal:Q});return C8(B)}async operationCustomEndpointCredential($,J,Z){let{CustomEndpointDeviceCredentialSchema:Q}=await import("./custom-endpoint-device-p2agcsk0.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 K=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 H8(K)}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 D$=new Set(["process.run.v1","process.full.v1","computer.use","browser.use"]),t0=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 y1($,J){if(D$.has($))return!1;if(t0.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($)||t0.has($)))return!1;return!0}import{accessSync as j$,constants as M$,existsSync as L$,statSync as I$}from"fs";import{basename as O$,isAbsolute as A$}from"path";var e0=["-lic"],w8="/bin/zsh",_$=new Set(["zsh","bash"]),j8=20000,f2=60000,P$=65536,T$=64,R$=8192,q$=new Set(["NODE_OPTIONS","PATH","ZDOTDIR","BASH_ENV","ENV"]),g$=["DYLD_","LD_"];function E$($){let J=$.toUpperCase();return q$.has(J)||g$.some((Z)=>J.startsWith(Z))}function M8($=process.env){return!0}function k$($){if(!A$($)||$.includes("\x00"))return!1;if(!_$.has(O$($)))return!1;try{if(!I$($).isFile())return!1;return j$($,M$.X_OK),!0}catch{return!1}}function q0($=process.env){if(process.platform==="win32")return D8()??w8;let J=$.SHELL?.trim();if(J&&k$(J))return J;return w8}function x2($=process.env){return M8($)&&L$(q0($))}function y2($=process.env){if(!M8($))throw new H("full_control_disabled","Full-control execution is unavailable on this Reason Device.")}function h2($){if(typeof $!=="string"||$.length===0||$.includes("\x00")||Buffer.byteLength($,"utf8")>P$)throw new H("invalid_payload","command is missing or too large.");return $}function m2($){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>T$)throw new H("invalid_payload","env has too many entries.");let Z={},Q=[];for(let[K,B]of J){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(K)||typeof B!=="string"||B.includes("\x00")||Buffer.byteLength(B,"utf8")>R$)throw new H("invalid_payload","env entry is invalid or too large.");if(E$(K)){Q.push(K);continue}Z[K]=B}return{forwarded:Z,ignored:Q}}async function L8($){let J=$.processEnv??process.env;if(y2(J),$.signal.aborted)throw new H("cancelled","Operation was cancelled.");let Z=h2($.command),Q=q0(J),{forwarded:K,ignored:B}=m2($.requestEnv),V=await $.spawn(Q,[...e0,Z],{cwd:$.cwd,timeoutMs:$.timeoutMs,signal:$.signal,env:{...J,...K}});return{exit_code:V.exitCode,signal:V.signal,stdout:V.stdout,stderr:V.stderr,timed_out:V.timedOut,truncated:V.truncated,shell:Q,shell_flags:[...e0],login:!0,interactive:!0,sandbox:"none",ignored_env:B}}function I8($=process.env){return{transport:"shell",shell:`${q0($)} ${e0.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:f2}}import{readFile as S$,readdir as b$,readlink as f$,realpath as x$}from"fs/promises";import{basename as y$,relative as h$,sep as m$}from"path";var M0="/proc",v$=250,O8=500,u$=50,p$=250,d$=1024,A8=4096,l$=1,s$=3,_8=9,c$="0A",n$=/^socket:\[(\d+)\]$/,v2={readDirectory:($)=>b$($),readLink:($)=>f$($),readTextFile:($)=>S$($,"utf8"),realPath:($)=>x$($)};function T8($,J){return J===$||J.startsWith(`${$}${m$}`)}function r$($,J){return h$($,J)||"."}async function R8($){let J;try{J=await $.readDirectory(M0)}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 q8($,J){try{let Q=(await J.readTextFile(`${M0}/${$}/comm`)).slice(0,A8).split(`
37
+ `,1)[0]?.trim();if(Q)return Q}catch{}try{let Q=(await J.readTextFile(`${M0}/${$}/cmdline`)).slice(0,A8).split("\x00",1)[0]?.trim();return Q?y$(Q):null}catch{return null}}async function g8($,J=v2){let Z;try{Z=await J.readLink(`${M0}/${$}/cwd`)}catch{return null}if(!Z)return null;try{return await J.realPath(Z)}catch{return null}}async function E8($,J=v2){let Z=[];for(let Q of await R8(J)){if(Z.length>=v$)break;let K=await g8(Q,J);if(!K||!T8($,K))continue;Z.push({pid:Q,command:await q8(Q,J),cwd:r$($,K)})}return{processes:Z}}function P8($){let J=[];for(let Z=0;Z<8;Z+=2)J.unshift(Number.parseInt($.slice(Z,Z+2),16));return J}function a$($){let J=[];for(let z=0;z<16;z+=2)J.push($[z]<<8|$[z+1]);if(J.slice(0,5).every((z)=>z===0)&&J[5]===65535)return`::ffff:${$.slice(12).join(".")}`;let Z=-1,Q=0,K=-1;for(let z=0;z<=J.length;z+=1){if(z<J.length&&J[z]===0){if(K<0)K=z;continue}if(K>=0){let W=z-K;if(W>Q)Z=K,Q=W;K=-1}}let B=J.map((z)=>z.toString(16));if(Q<2)return B.join(":");let V=B.slice(0,Z).join(":"),U=B.slice(Z+Q).join(":");return`${V}::${U}`}function i$($,J){if(/^[0-9A-Fa-f]{8}$/.test($)){let Z=P8($);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(...P8($.slice(Q*8,Q*8+8)));if(Z.every((Q)=>Q===0))return`*:${J}`;return`[${a$(Z)}]:${J}`}return null}function o$($,J){let Z=[];for(let Q of $.split(`
38
+ `).slice(1)){if(Z.length>=J)break;let K=Q.trim().split(/\s+/);if(K.length<=_8)continue;if(K[s$]?.toUpperCase()!==c$)continue;let B=K[l$]??"",V=B.lastIndexOf(":");if(V<0)continue;let U=Number.parseInt(B.slice(V+1),16);if(!Number.isInteger(U)||U<=0||U>65535)continue;let z=i$(B.slice(0,V),U),W=K[_8];if(!z||!W||!/^[0-9]+$/.test(W))continue;Z.push({inode:W,port:U,address:z})}return Z}async function t$($){let J=[];for(let Z of["tcp","tcp6"]){if(J.length>=O8)break;let Q;try{Q=await $.readTextFile(`${M0}/net/${Z}`)}catch{continue}J.push(...o$(Q,O8-J.length))}return J}async function e$($,J){let Z=new Map;if($.size===0)return Z;for(let Q of await R8(J)){if(Z.size>=$.size)break;let K;try{K=await J.readDirectory(`${M0}/${Q}/fd`)}catch{continue}for(let B of K.slice(0,d$)){let V;try{V=await J.readLink(`${M0}/${Q}/fd/${B}`)}catch{continue}let U=V.match(n$)?.[1];if(!U||!$.has(U)||Z.has(U))continue;Z.set(U,Q)}}return Z}async function k8($,J=v2){let Z=await t$(J),Q=await e$(new Set(Z.map((G)=>G.inode)),J),K=[];for(let G of Z){let F=Q.get(G.inode);if(F===void 0)continue;K.push({pid:F,port:G.port,address:G.address})}K.sort((G,F)=>G.pid-F.pid||G.port-F.port||(G.address<F.address?-1:G.address>F.address?1:0));let B=[...new Set(K.map((G)=>G.pid))].slice(0,u$),V=await Promise.all(B.map(async(G)=>[G,await g8(G,J)])),U=new Map(V),z=K.filter((G)=>{let F=U.get(G.pid);return Boolean(F&&T8($,F))}),W=new Map(await Promise.all([...new Set(z.map((G)=>G.pid))].map(async(G)=>[G,await q8(G,J)])));return{ports:z.slice(0,p$).map((G)=>({pid:G.pid,command:W.get(G.pid)??null,address:G.address}))}}import{posix as p2}from"path";var h1=200,$J=250,JJ=250;async function m1($,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=[],K=null;for(let B of Z.stdout.split(/\r?\n/))if(B.startsWith("p")){let V=Number(B.slice(1));if(K=Number.isInteger(V)&&V>0?{pid:V,command:null,names:[]}:null,K)Q.push(K)}else if(K&&B.startsWith("c"))K.command=B.slice(1)||null;else if(K&&B.startsWith("n"))K.names.push(B.slice(1));return Q}function u2($,J){return J===$||J.startsWith($==="/"?$:`${$}/`)}var S8="/System/Volumes/Data",ZJ=["/tmp","/var","/etc"];function d2($){let J=p2.normalize($);if(J.startsWith(`${S8}/`))J=J.slice(S8.length);return ZJ.find((Q)=>J===Q||J.startsWith(`${Q}/`))?`/private${J}`:J}function b8($){return $&&p2.isAbsolute($)?d2($):null}async function f8($,J){let Z=new Map;for(let Q=0;Q<J.length;Q+=h1){let K=J.slice(Q,Q+h1).join(",");for(let B of await m1($,["-a","-p",K,"-d","cwd","-Fpcn"]))Z.set(B.pid,{command:B.command,cwd:b8(B.names[0])})}return Z}async function x8($,J){let Z=d2($),Q=(await m1(J,["-d","cwd","-Fpn"])).filter((B)=>{let V=b8(B.names[0]);return V!==null&&u2(Z,V)}).map((B)=>B.pid).slice(0,$J),K=await f8(J,Q);return{processes:Q.flatMap((B)=>{let V=K.get(B);return V?.cwd&&u2(Z,V.cwd)?[{pid:B,command:V.command,cwd:p2.relative(Z,V.cwd)||"."}]:[]})}}async function y8($,J){let Z=d2($),Q=["-nP","-iTCP","-sTCP:LISTEN","-Fpcn"],K=await m1(J,Q),B=await f8(J,K.map((W)=>W.pid)),V=K.map((W)=>W.pid).filter((W)=>{let G=B.get(W)?.cwd;return Boolean(G&&u2(Z,G))});if(V.length===0)return{ports:[]};let U=new Set(K.flatMap((W)=>W.names.map((G)=>`${W.pid} ${G}`))),z=[];for(let W=0;W<V.length;W+=h1){let G=V.slice(W,W+h1).join(",");for(let F of await m1(J,["-a","-p",G,...Q]))for(let Y of F.names)if(U.has(`${F.pid} ${Y}`))z.push({pid:F.pid,command:F.command,address:Y})}return{ports:z.slice(0,JJ)}}import{join as HJ}from"path";import{spawn as XJ}from"child_process";import{randomUUID as WJ}from"crypto";import{chmodSync as v8,lstatSync as u8,mkdirSync as zJ,readdirSync as FJ,statSync as YJ,unlinkSync as NJ}from"fs";import{join as s2}from"path";var l2={targets:24,assets:128,sourceFiles:2000,sourceBytes:20000000,outputBytes:20000000};var v1=($,J=0,Z=1e6)=>typeof $==="number"&&Number.isFinite($)&&$>=J&&$<=Z;var L0=()=>{throw Error("proof_visual_contract_invalid")};class h8 extends Error{constructor(){super("proof_visual_contract_invalid")}}function KJ($){if(!$1($)||$.version!==1)return L0();if(typeof $.route!=="string"||!$.route.startsWith("/")||$.route.length>512||/[\x00-\x20\x7f\\?#%]/.test($.route)||$.route.startsWith("//"))throw new h8;if(!$1($.viewport)||!v1($.viewport.width,1,4096)||!v1($.viewport.height,1,4096)||!Array.isArray($.targets)||$.targets.length<1||$.targets.length>l2.targets||Object.keys($).some((Q)=>!["version","route","viewport","targets","additionalViewports"].includes(Q)))return L0();let J=$.targets.map((Q)=>{if(!$1(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((K)=>!["id","selector"].includes(K)))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((K)=>{if(!$1(K)||!v1(K.width,1,4096)||!Number.isInteger(K.width)||!v1(K.height,1,4096)||!Number.isInteger(K.height)||Object.keys(K).some((B)=>!["width","height"].includes(B)))return L0();return{width:K.width,height:K.height}});let Q=[$.viewport,...Z].map((K)=>`${K.width}x${K.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"],GJ=[...VJ,"prUrl","headSha","skillDigest","evidenceKind"],HB=[...GJ,"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 m8($){return UJ[$].directory}var p8=10485760;function d8($={}){let J=$.directory??m8("video/webm"),Z=null;return{async start(Q){if(Z)throw Error("cloud_browser_recording_active");let K=Q?.seconds;if(!Number.isInteger(K)||Number(K)<1||Number(K)>15||!Q||Object.keys(Q).some((D)=>D!=="seconds"))throw Error("cloud_browser_recording_seconds_1_to_15_required");zJ(J,{recursive:!0,mode:457});let B=u8(J);if(!B.isDirectory()||B.isSymbolicLink()||B.uid!==process.getuid?.())throw Error("cloud_browser_recording_directory_invalid");v8(J,457);let V=FJ(J).filter((D)=>/^[a-f0-9-]{36}\.webm$/.test(D)).map((D)=>({name:D,time:YJ(s2(J,D)).mtimeMs})).sort((D,w)=>w.time-D.time);for(let D of V.slice(9))NJ(s2(J,D.name));let U=s2(J,`${WJ()}.webm`),z=["-f","x11grab","-framerate","12","-i",$.display??":99"],W=($.spawn??XJ)($.ffmpeg??"ffmpeg",["-nostdin","-hide_banner","-loglevel","error","-y",...z,"-t",String(K),"-vf","scale=1280:-2","-c:v","libvpx","-deadline","realtime","-b:v","700k","-an","-fs",String(p8),"-progress","pipe:1",U],{stdio:["ignore","pipe","ignore"],...$.env?{env:$.env}:{}}),G,F,Y=!1,N=new Promise((D,w)=>{G=D,F=w});W.stdout.on("data",(D)=>{if(/frame=\s*[1-9]/.test(String(D)))Y=!0,G()});let C=new Promise((D,w)=>{W.once("error",()=>{F(Error("cloud_browser_recording_unavailable")),w(Error("cloud_browser_recording_unavailable"))}),W.once("exit",(M)=>{try{if(M!==0&&M!==255)throw Error();let I=u8(U);if(!Y||!I.isFile()||I.isSymbolicLink()||I.uid!==process.getuid?.()||I.size<128||I.size>p8+65536)throw Error();v8(U,420),G(),D({path:U,mimeType:"video/webm"})}catch{F(Error("cloud_browser_recording_failed")),w(Error("cloud_browser_recording_failed"))}})});C.catch(()=>{});let L=setTimeout(()=>W.kill("SIGKILL"),(Number(K)+5)*1000);C.finally(()=>clearTimeout(L)).catch(()=>{}),Z={done:C,stop:()=>{return W.kill("SIGINT"),C}};try{await N}catch(D){throw Z=null,D}return{recording:!0,seconds:Number(K)}},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 c8($,J={}){if($.executionMode!=="unsandboxed"||!$.runtimeDirectory||(J.platform??process.platform)!=="linux")return null;let Z=(J.components??n8)(),Q=Z?.features.display?Z.ffmpeg:null;if(!Q)return null;let K=HJ($.runtimeDirectory,"recordings"),B=null;return{async start(V){let U=await(J.desktop??s8)();return B??=d8({directory:K,display:U.display,ffmpeg:Q,env:{HOME:l8(),PATH:"/usr/local/bin:/usr/bin:/bin",XAUTHORITY:U.xauthority},...J.spawn?{spawn:J.spawn}:{}}),B.start(V)},async stop(){if(!B)throw Error("cloud_browser_recording_not_started");return B.stop()},async close(){await B?.close()}}}import{spawn as W3}from"child_process";import{createHash as fJ,randomUUID as xJ}from"crypto";import{existsSync as J0,mkdirSync as B3,mkdtempSync as z3,readdirSync as a1,readFileSync as F3,renameSync as yJ,rmSync as Q1,statSync as s1,writeFileSync as hJ}from"fs";import{homedir as Y3,tmpdir as N5}from"os";import{basename as H5,dirname as V3,join as q,relative as C5,resolve as G3,sep as w5}from"path";var n=X.string().min(1).max(200),$0=X.number().finite().min(0).max(1e4),u1=X.string().min(1).max(4096).refine(($)=>!$.includes("\x00")),r8=X.string().regex(/^[A-Za-z0-9][A-Za-z0-9.-]{0,254}$/),n2=X.object({id:X.string().min(1).max(500).optional(),label:X.string().min(1).max(500).optional()}).strict(),r2=["home","lock","side_button","siri","apple_pay"],CJ=X.enum(["tree","screenshot","both","none"]),wJ=X.object({...n2.shape,gone:X.boolean().optional()}).strict().refine(($)=>Boolean($.id||$.label),"wait_for needs an id or label"),N0={observe:CJ.optional(),wait_for:wJ.optional(),timeout:X.number().min(0).max(20).optional()},c2=X.discriminatedUnion("action",[X.object({action:X.literal("tap"),x:$0.optional(),y:$0.optional(),...n2.shape,duration:X.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"),X.object({action:X.literal("swipe"),x:$0,y:$0,x2:$0,y2:$0,duration:X.number().min(0.05).max(5).optional()}).strict(),X.object({action:X.literal("type"),text:X.string().min(1).max(4000)}).strict(),X.object({action:X.literal("button"),name:X.enum(r2)}).strict(),X.object({action:X.literal("sleep"),seconds:X.number().min(0).max(10)}).strict()]),a2=X.discriminatedUnion("action",[X.object({action:X.literal("devices")}).strict(),X.object({action:X.literal("boot"),device:n}).strict(),X.object({action:X.literal("shutdown"),device:n}).strict(),X.object({action:X.literal("build"),path:u1.optional(),scheme:X.string().min(1).max(200).optional(),configuration:X.string().min(1).max(100).optional(),device:n.optional(),wait:X.boolean().optional()}).strict(),X.object({action:X.literal("run"),path:u1.optional(),scheme:X.string().min(1).max(200).optional(),configuration:X.string().min(1).max(100).optional(),device:n.optional(),steps:X.array(X.lazy(()=>c2)).max(30).optional(),...N0}).strict(),X.object({action:X.literal("build_status"),build_id:X.string().regex(/^build-[0-9a-z-]{4,64}$/),device:n.optional(),wait:X.boolean().optional()}).strict(),X.object({action:X.literal("launch"),device:n.optional(),app_path:u1.optional(),bundle_id:r8.optional(),steps:X.array(X.lazy(()=>c2)).max(30).optional(),...N0}).strict().refine(($)=>Boolean($.app_path)!==Boolean($.bundle_id),"pass exactly one of app_path or bundle_id"),X.object({action:X.literal("terminate"),device:n.optional(),bundle_id:r8}).strict(),X.object({action:X.literal("logs"),device:n.optional(),after:X.number().int().min(0).optional()}).strict(),X.object({action:X.literal("screenshot"),device:n.optional(),scale:X.union([X.literal(1),X.literal(2)]).optional(),save_path:u1.optional()}).strict(),X.object({action:X.literal("chrome"),device:n.optional()}).strict(),X.object({action:X.literal("inspect"),device:n.optional()}).strict(),X.object({action:X.literal("tap"),device:n.optional(),x:$0.optional(),y:$0.optional(),...n2.shape,duration:X.number().min(0).max(10).optional(),...N0}).strict().refine(($)=>$.x!==void 0&&$.y!==void 0||Boolean($.id||$.label),"pass x and y, or an id or label"),X.object({action:X.literal("swipe"),device:n.optional(),x:$0,y:$0,x2:$0,y2:$0,duration:X.number().min(0.05).max(5).optional(),...N0}).strict(),X.object({action:X.literal("type"),device:n.optional(),text:X.string().min(1).max(4000),...N0}).strict(),X.object({action:X.literal("button"),device:n.optional(),name:X.enum(r2),...N0}).strict(),X.object({action:X.literal("open_url"),device:n.optional(),url:X.string().min(1).max(4000),...N0}).strict(),X.object({action:X.literal("steps"),device:n.optional(),steps:X.array(c2).min(1).max(30),...N0}).strict(),X.object({action:X.literal("appearance"),device:n.optional(),mode:X.enum(["light","dark"])}).strict()]),a8=X.object({udid:X.string(),name:X.string(),runtime:X.string(),state:X.enum(["booted","shutdown","booting","shutting_down"]),kind:X.enum(["iphone","ipad","other"])}).strict(),bB=X.object({text:X.string(),error:X.string().optional(),device:a8.optional(),devices:X.array(a8).optional(),image:X.object({mime:X.literal("image/jpeg"),data:X.string(),width:X.number(),height:X.number()}).strict().optional(),build:X.object({id:X.string(),status:X.enum(["running","succeeded","failed"]),app_path:X.string().optional(),bundle_id:X.string().optional(),errors:X.array(X.string()),log_tail:X.string(),elapsed_ms:X.number()}).strict().optional(),logs:X.object({lines:X.array(X.string()),next:X.number()}).strict().optional(),screen:X.string().optional(),chrome:X.object({identifier:X.string(),screen:X.object({width:X.number(),height:X.number()}).strict(),inset:X.object({top:X.number(),left:X.number(),bottom:X.number(),right:X.number()}).strict(),padding:X.object({top:X.number(),left:X.number(),bottom:X.number(),right:X.number()}).strict(),screen_mask:X.string().optional(),pieces:X.record(X.enum(["topLeft","top","topRight","right","bottomRight","bottom","bottomLeft","left"]),X.object({image:X.string(),width:X.number(),height:X.number()}).strict()),buttons:X.array(X.object({name:X.string(),image:X.string(),x:X.number(),y:X.number(),width:X.number(),height:X.number()}).strict())}).strict().optional()}).strict();var fB=X.object({device_id:X.uuid().optional(),root_id:X.uuid().optional()}),p1={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:[...r2],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."}},o8=a2.options.map(($)=>$.shape).filter(($)=>$.action.value!=="chrome"),DJ={tap:[{required:["x","y"]},{required:["id"]},{required:["label"]}],launch:[{required:["app_path"],without:["bundle_id"]},{required:["bundle_id"],without:["app_path"]}]},i8=new Set;function jJ($,J){let{description:Z,...Q}=$==="steps"&&J==="steps"?{...p1.steps,minItems:1}:p1[$];if(Z===void 0||i8.has($))return Q;return i8.add($),{...Q,description:Z}}var MJ=o8.flatMap(($)=>{let J=$.action.value,Z=Object.keys($).filter((K)=>Object.hasOwn(p1,K)),Q=Z.filter((K)=>!$[K].safeParse(void 0).success);return(DJ[J]??[{required:[]}]).map((K)=>({type:"object",properties:Object.fromEntries([["action",{type:"string",const:J}],...["device_id","root_id",...Z].filter((B)=>!K.without?.includes(B)).map((B)=>[B,jJ(B,J)])]),required:["action",...Q,...K.required],additionalProperties:!1}))}),LJ={type:"object",properties:{action:{type:"string",enum:o8.map(($)=>$.action.value)},...p1},required:["action"],additionalProperties:!1},xB={...LJ,anyOf:MJ};import{spawn as e2}from"child_process";import{createHash as OJ}from"crypto";import{existsSync as o2,mkdirSync as d1,mkdtempSync as AJ,readdirSync as t8,readFileSync as e8,renameSync as _J,rmSync as $5,symlinkSync as t2,writeFileSync as J1}from"fs";import{homedir as PJ}from"os";import{dirname as K5,join as k}from"path";import{createInterface as TJ}from"readline";var i2=`// Reason's simulator host: one warm process per booted iOS Simulator.
39
+ //
40
+ // Built on the Mac on first use (cli/simulator-host.ts) against the MIT
41
+ // FBSimulatorControl frameworks that the pinned AXe ships, so loading
42
+ // SimulatorKit and connecting to the simulator happen once per process
43
+ // instead of once per action (about a second each, three under load).
44
+ //
45
+ // simulator-host serve <udid>
46
+ // Newline JSON requests on stdin, one newline JSON reply each on stdout,
47
+ // in order: {"id":1,"op":"tap","x":100,"y":200} -> {"id":1,"ok":true}.
48
+ // Ops: touch (phase down|move|up), tap, swipe, button, text, key, tree.
49
+ // Coordinates are device points. \`tree\` answers AXe describe-ui's JSON.
50
+ // simulator-host stream <udid> <fps> <max pixels> <kbps>
51
+ // H.264 (Main, level 4.2) as Annex-B on stdout, encoded with VideoToolbox
52
+ // straight from the simulator's framebuffer. Every keyframe carries
53
+ // SPS/PPS, and every access unit is followed by an AUD, so a reader that
54
+ // splits at AUDs has each frame as soon as it is written.
55
+ //
56
+ // Both modes exit when stdin closes, so they never outlive the worker.
57
+
58
+ import CoreMedia
59
+ import CoreVideo
60
+ import Darwin
61
+ import FBControlCore
62
+ import FBSimulatorControl
63
+ import Foundation
64
+ import IOSurface
65
+ import VideoToolbox
66
+
67
+ @objc final class SilentReporter: NSObject, FBEventReporter {
68
+ var metadata: [String: String] = [:]
69
+ func report(_ subject: FBEventReporterSubject) {}
70
+ func addMetadata(_ metadata: [String: String]) {}
71
+ }
72
+
73
+ let logger: FBControlCoreLogger = FBControlCoreLoggerFactory.systemLoggerWriting(toStderr: false, withDebugLogging: false)
74
+
75
+ func fail(_ message: String) -> Never {
76
+ FileHandle.standardError.write(Data((message + "\\n").utf8))
77
+ exit(1)
78
+ }
79
+
80
+ /// Writes all of \`data\` to stdout; a closed reader ends the process.
81
+ func writeOut(_ data: Data) {
82
+ data.withUnsafeBytes { (buffer: UnsafeRawBufferPointer) in
83
+ var offset = 0
84
+ while offset < buffer.count {
85
+ let written = Darwin.write(1, buffer.baseAddress!.advanced(by: offset), buffer.count - offset)
86
+ if written <= 0 {
87
+ if written < 0 && errno == EINTR { continue }
88
+ exit(0)
89
+ }
90
+ offset += written
91
+ }
92
+ }
93
+ }
94
+
95
+ @MainActor
96
+ func simulator(_ udid: String) async throws -> FBSimulator {
97
+ try FBSimulatorControlFrameworkLoader.essentialFrameworks.loadPrivateFrameworks(logger)
98
+ try FBSimulatorControlFrameworkLoader.xcodeFrameworks.loadPrivateFrameworks(logger)
99
+ FBControlCoreGlobalConfiguration.defaultLogger = logger
100
+ let configuration = FBSimulatorControlConfiguration(deviceSetPath: nil, logger: logger, reporter: SilentReporter())
101
+ let set = try FBSimulatorControl.withConfiguration(configuration).set
102
+ guard let target = set.allSimulators.first(where: { $0.udid == udid }) else { fail("simulator_not_found") }
103
+ guard target.state == .booted else { fail("simulator_not_booted") }
104
+ return target
105
+ }
106
+
107
+ // MARK: - serve
108
+
109
+ /// US keyboard: character -> (HID usage, shift).
110
+ let keyboard: [Character: (UInt32, Bool)] = {
111
+ var map: [Character: (UInt32, Bool)] = [:]
112
+ for (index, letter) in "abcdefghijklmnopqrstuvwxyz".enumerated() {
113
+ map[letter] = (UInt32(4 + index), false)
114
+ map[Character(letter.uppercased())] = (UInt32(4 + index), true)
115
+ }
116
+ for (index, digit) in "1234567890".enumerated() { map[digit] = (UInt32(30 + index), false) }
117
+ for (index, symbol) in "!@#$%^&*()".enumerated() { map[symbol] = (UInt32(30 + index), true) }
118
+ let plain: [(Character, UInt32)] = [("\\n", 40), ("\\t", 43), (" ", 44), ("-", 45), ("=", 46), ("[", 47), ("]", 48),
119
+ ("\\\\", 49), (";", 51), ("'", 52), ("\`", 53), (",", 54), (".", 55), ("/", 56)]
120
+ let shifted: [(Character, UInt32)] = [("_", 45), ("+", 46), ("{", 47), ("}", 48), ("|", 49), (":", 51), ("\\"", 52),
121
+ ("~", 53), ("<", 54), (">", 55), ("?", 56)]
122
+ for (character, usage) in plain { map[character] = (usage, false) }
123
+ for (character, usage) in shifted { map[character] = (usage, true) }
124
+ return map
125
+ }()
126
+
127
+ let buttons: [String: FBSimulatorHIDButton] = [
128
+ "home": .homeButton, "lock": .lock, "side_button": .sideButton, "siri": .siri, "apple_pay": .applePay,
129
+ ]
130
+
131
+ /// AXe describe-ui's keys (its schema), so the worker parses one format either way.
132
+ let treeKeys: Set<FBAXKeys> = [.label, .frame, .value, .uniqueID, .type, .title, .frameDict, .help, .enabled,
133
+ .customActions, .role, .roleDescription, .subrole, .contentRequired, .pid]
134
+
135
+ func withTraits(_ value: Any) -> Any {
136
+ if let list = value as? [Any] { return list.map(withTraits) }
137
+ guard var element = value as? [String: Any] else { return value }
138
+ for (key, child) in element { element[key] = withTraits(child) }
139
+ if element["type"] != nil && element["traits"] == nil { element["traits"] = [String]() }
140
+ return element
141
+ }
142
+
143
+ func hasChildren(_ value: Any) -> Bool {
144
+ let roots = (value as? [[String: Any]]) ?? ((value as? [String: Any]).map { [$0] } ?? [])
145
+ return roots.contains { (($0["children"] as? [Any])?.isEmpty == false) }
146
+ }
147
+
148
+ @MainActor
149
+ func readTree(_ target: FBSimulator) async throws -> String {
150
+ var latest: Any = []
151
+ for attempt in 0..<4 {
152
+ let element = try await target.accessibilityElementForFrontmostApplication()
153
+ defer { element.close() }
154
+ let response = try element.serialize(with: FBAccessibilityRequestOptions(nestedFormat: true, keys: treeKeys))
155
+ latest = withTraits(response.elements)
156
+ if hasChildren(latest) { break }
157
+ if attempt < 3 { try await Task.sleep(for: .milliseconds(50 << attempt)) }
158
+ }
159
+ let data = try JSONSerialization.data(withJSONObject: latest)
160
+ return String(decoding: data, as: UTF8.self)
161
+ }
162
+
163
+ @MainActor
164
+ func handle(_ request: [String: Any], target: FBSimulator, hid: FBSimulatorHID) async throws -> [String: Any] {
165
+ let number = { (key: String) -> Double in
166
+ guard let value = request[key] as? Double else { throw NSError(domain: "simulator-host", code: 1, userInfo: [NSLocalizedDescriptionKey: "missing \\(key)"]) }
167
+ return value
168
+ }
169
+ switch request["op"] as? String {
170
+ case "touch":
171
+ let direction: FBSimulatorHIDDirection = (request["phase"] as? String) == "up" ? .up : .down
172
+ try await hid.send(event: .touch(direction: direction, x: try number("x"), y: try number("y")), logger: logger)
173
+ case "tap":
174
+ let duration = request["duration"] as? Double ?? 0
175
+ let event: FBSimulatorHIDEvent = duration > 0
176
+ ? .tapAt(x: try number("x"), y: try number("y"), duration: duration) : .tapAt(x: try number("x"), y: try number("y"))
177
+ try await hid.send(event: event, logger: logger)
178
+ case "swipe":
179
+ try await hid.send(event: .swipe(try number("x"), yStart: try number("y"), xEnd: try number("x2"), yEnd: try number("y2"),
180
+ delta: request["delta"] as? Double ?? 10, duration: request["duration"] as? Double ?? 0.3), logger: logger)
181
+ case "button":
182
+ guard let button = buttons[request["name"] as? String ?? ""] else { throw NSError(domain: "simulator-host", code: 1, userInfo: [NSLocalizedDescriptionKey: "unknown button"]) }
183
+ try await hid.send(event: .shortButtonPress(button), logger: logger)
184
+ case "text":
185
+ var events: [FBSimulatorHIDEvent] = []
186
+ for character in request["text"] as? String ?? "" {
187
+ guard let (usage, shift) = keyboard[character] else {
188
+ throw NSError(domain: "simulator-host", code: 2, userInfo: [NSLocalizedDescriptionKey: "unsupported character"])
189
+ }
190
+ if shift { events.append(.keyboard(direction: .down, keyCode: 225)) }
191
+ events.append(.keyboard(direction: .down, keyCode: usage))
192
+ events.append(.keyboard(direction: .up, keyCode: usage))
193
+ if shift { events.append(.keyboard(direction: .up, keyCode: 225)) }
194
+ }
195
+ if !events.isEmpty { try await hid.send(event: .composite(events), logger: logger) }
196
+ case "key":
197
+ let direction: FBSimulatorHIDDirection = (request["down"] as? Bool) == false ? .up : .down
198
+ try await hid.send(event: .keyboard(direction: direction, keyCode: UInt32(try number("usage"))), logger: logger)
199
+ case "tree":
200
+ return ["tree": try await readTree(target)]
201
+ default:
202
+ throw NSError(domain: "simulator-host", code: 1, userInfo: [NSLocalizedDescriptionKey: "unknown op"])
203
+ }
204
+ return [:]
205
+ }
206
+
207
+ @MainActor
208
+ func serve(_ udid: String) async {
209
+ let target: FBSimulator
210
+ let hid: FBSimulatorHID
211
+ do {
212
+ target = try await simulator(udid)
213
+ hid = try await target.connectToHID()
214
+ } catch {
215
+ fail("connect_failed: \\(error.localizedDescription)")
216
+ }
217
+ writeOut(Data("{\\"ready\\":true}\\n".utf8))
218
+ do {
219
+ for try await line in FileHandle.standardInput.bytes.lines {
220
+ guard let request = (try? JSONSerialization.jsonObject(with: Data(line.utf8))) as? [String: Any] else { continue }
221
+ var reply: [String: Any]
222
+ do {
223
+ reply = try await handle(request, target: target, hid: hid)
224
+ reply["ok"] = true
225
+ } catch {
226
+ reply = ["ok": false, "error": error.localizedDescription]
227
+ }
228
+ reply["id"] = request["id"] ?? 0
229
+ var data = (try? JSONSerialization.data(withJSONObject: reply)) ?? Data("{\\"ok\\":false}".utf8)
230
+ data.append(0x0A)
231
+ writeOut(data)
232
+ }
233
+ } catch {}
234
+ exit(0)
235
+ }
236
+
237
+ // MARK: - stream
238
+
239
+ let startCode = Data([0, 0, 0, 1])
240
+ let accessUnitDelimiter = Data([0, 0, 0, 1, 0x09, 0xF0])
241
+
242
+ struct BitReader {
243
+ let bytes: [UInt8]
244
+ var position = 0
245
+ mutating func bit() -> UInt32? {
246
+ guard position < bytes.count * 8 else { return nil }
247
+ defer { position += 1 }
248
+ return UInt32(bytes[position >> 3] >> (7 - UInt8(position & 7)) & 1)
249
+ }
250
+ mutating func bits(_ count: Int) -> UInt32? {
251
+ var value: UInt32 = 0
252
+ for _ in 0..<count { guard let next = bit() else { return nil }; value = value << 1 | next }
253
+ return value
254
+ }
255
+ mutating func ue() -> UInt32? {
256
+ var zeros = 0
257
+ while true { guard let next = bit() else { return nil }; if next == 1 { break }; zeros += 1; if zeros > 31 { return nil } }
258
+ guard let rest = bits(zeros) else { return nil }
259
+ return (1 << zeros) - 1 + rest
260
+ }
261
+ }
262
+
263
+ struct BitWriter {
264
+ var bytes: [UInt8] = []
265
+ var count = 0
266
+ mutating func bit(_ value: UInt32) {
267
+ if count & 7 == 0 { bytes.append(0) }
268
+ if value & 1 == 1 { bytes[bytes.count - 1] |= 1 << (7 - UInt8(count & 7)) }
269
+ count += 1
270
+ }
271
+ mutating func bits(_ value: UInt32, _ width: Int) { for shift in stride(from: width - 1, through: 0, by: -1) { bit(value >> UInt32(shift)) } }
272
+ mutating func ue(_ value: UInt32) {
273
+ let coded = value + 1
274
+ let width = 32 - coded.leadingZeroBitCount
275
+ bits(0, width - 1)
276
+ bits(coded, width)
277
+ }
278
+ }
279
+
280
+ /// The SPS with a VUI that says frames come out in decode order, one at a time. VideoToolbox writes no
281
+ /// bitstream restriction, so a browser decoder may hold the newest frames back for reordering; on a
282
+ /// screen that stops changing, the last one would never be shown. Any SPS this does not expect is kept.
283
+ func lowDelaySps(_ nal: Data) -> Data {
284
+ var raw: [UInt8] = []
285
+ var zeros = 0
286
+ for byte in nal.dropFirst() {
287
+ if zeros >= 2 && byte == 3 { zeros = 0; continue }
288
+ raw.append(byte)
289
+ zeros = byte == 0 ? zeros + 1 : 0
290
+ }
291
+ var reader = BitReader(bytes: raw)
292
+ var writer = BitWriter()
293
+ func copyBits(_ width: Int) -> UInt32? { guard let value = reader.bits(width) else { return nil }; writer.bits(value, width); return value }
294
+ func copyUe() -> UInt32? { guard let value = reader.ue() else { return nil }; writer.ue(value); return value }
295
+ guard let profile = copyBits(8), copyBits(16) != nil, copyUe() != nil else { return nal }
296
+ if [100, 110, 122, 244, 44, 83, 86, 118, 128, 138, 139, 134, 135].contains(profile) {
297
+ guard let chroma = copyUe() else { return nal }
298
+ if chroma == 3 { guard copyBits(1) != nil else { return nal } }
299
+ guard copyUe() != nil, copyUe() != nil, copyBits(1) != nil, let scaling = copyBits(1), scaling == 0 else { return nal }
300
+ }
301
+ guard copyUe() != nil, let pocType = copyUe() else { return nal }
302
+ if pocType == 0 { guard copyUe() != nil else { return nal } } else if pocType != 2 { return nal }
303
+ guard let references = copyUe(), copyBits(1) != nil, copyUe() != nil, copyUe() != nil, let frameOnly = copyBits(1) else { return nal }
304
+ if frameOnly == 0 { guard copyBits(1) != nil else { return nal } }
305
+ guard copyBits(1) != nil, let cropping = copyBits(1) else { return nal }
306
+ if cropping == 1 { for _ in 0..<4 { guard copyUe() != nil else { return nal } } }
307
+ guard reader.bits(1) == 0 else { return nal }
308
+ writer.bit(1) // vui_parameters_present_flag
309
+ writer.bits(0, 6) // aspect ratio, overscan, video signal, chroma location, timing, NAL HRD
310
+ writer.bit(0) // VCL HRD
311
+ writer.bit(0) // pic_struct_present_flag
312
+ writer.bit(1) // bitstream_restriction_flag
313
+ writer.bit(1) // motion_vectors_over_pic_boundaries_flag
314
+ writer.ue(2); writer.ue(1); writer.ue(16); writer.ue(16)
315
+ writer.ue(0) // max_num_reorder_frames
316
+ writer.ue(max(1, references)) // max_dec_frame_buffering
317
+ writer.bit(1) // rbsp_stop_one_bit
318
+ while writer.count & 7 != 0 { writer.bit(0) }
319
+ var out = Data([nal.first!])
320
+ zeros = 0
321
+ for byte in writer.bytes {
322
+ if zeros >= 2 && byte <= 3 { out.append(3); zeros = 0 }
323
+ out.append(byte)
324
+ zeros = byte == 0 ? zeros + 1 : 0
325
+ }
326
+ return out
327
+ }
328
+
329
+ final class Encoder: NSObject, FBFramebufferConsumer, @unchecked Sendable {
330
+ let queue = DispatchQueue(label: "simulator-host.encode")
331
+ let fps: Int
332
+ let maxPixels: Double
333
+ let kbps: Int
334
+ var surface: IOSurface?
335
+ var dirty = true
336
+ var forceKey = true
337
+ var session: VTCompressionSession?
338
+ var transfer: VTPixelTransferSession?
339
+ var size = (width: 0, height: 0)
340
+ var frames: Int64 = 0
341
+
342
+ init(fps: Int, maxPixels: Double, kbps: Int) {
343
+ self.fps = fps
344
+ self.maxPixels = maxPixels
345
+ self.kbps = kbps
346
+ }
347
+
348
+ func didChange(_ surface: IOSurface?) {
349
+ self.surface = surface
350
+ dirty = true
351
+ forceKey = true
352
+ }
353
+
354
+ func didReceiveDamageRect() { dirty = true }
355
+
356
+ /// The encoded picture: the framebuffer scaled to stay within \`maxPixels\`, even sides.
357
+ func outputSize(_ surface: IOSurface) -> (width: Int, height: Int) {
358
+ let width = Double(IOSurfaceGetWidth(surface)), height = Double(IOSurfaceGetHeight(surface))
359
+ let fit = min(1, (maxPixels / (width * height)).squareRoot())
360
+ let even = { (value: Double) in max(2, Int(value * fit) / 2 * 2) }
361
+ return (even(width), even(height))
362
+ }
363
+
364
+ func makeSession(_ width: Int, _ height: Int) {
365
+ if let session { VTCompressionSessionInvalidate(session) }
366
+ var created: VTCompressionSession?
367
+ let status = VTCompressionSessionCreate(allocator: nil, width: Int32(width), height: Int32(height),
368
+ codecType: kCMVideoCodecType_H264, encoderSpecification: nil, imageBufferAttributes: nil,
369
+ compressedDataAllocator: nil, outputCallback: nil, refcon: nil, compressionSessionOut: &created)
370
+ guard status == noErr, let created else { fail("encoder_failed \\(status)") }
371
+ let set = { (key: CFString, value: CFTypeRef) in _ = VTSessionSetProperty(created, key: key, value: value) }
372
+ set(kVTCompressionPropertyKey_RealTime, kCFBooleanTrue)
373
+ set(kVTCompressionPropertyKey_ProfileLevel, kVTProfileLevel_H264_Main_4_2)
374
+ set(kVTCompressionPropertyKey_AllowFrameReordering, kCFBooleanFalse)
375
+ set(kVTCompressionPropertyKey_MaxFrameDelayCount, 0 as CFNumber)
376
+ set(kVTCompressionPropertyKey_ExpectedFrameRate, fps as CFNumber)
377
+ set(kVTCompressionPropertyKey_AverageBitRate, (kbps * 1000) as CFNumber)
378
+ // Keyframes come from a (re)start or a framebuffer change; this is only a safety net.
379
+ set(kVTCompressionPropertyKey_MaxKeyFrameIntervalDuration, 60 as CFNumber)
380
+ VTCompressionSessionPrepareToEncodeFrames(created)
381
+ session = created
382
+ size = (width, height)
383
+ var createdTransfer: VTPixelTransferSession?
384
+ VTPixelTransferSessionCreate(allocator: nil, pixelTransferSessionOut: &createdTransfer)
385
+ transfer = createdTransfer
386
+ }
387
+
388
+ func tick() {
389
+ guard dirty, let surface else { return }
390
+ dirty = false
391
+ let wanted = outputSize(surface)
392
+ if session == nil || wanted.width != size.width || wanted.height != size.height { makeSession(wanted.width, wanted.height) }
393
+ guard let session, let transfer, let pool = VTCompressionSessionGetPixelBufferPool(session) else { return }
394
+ var source: Unmanaged<CVPixelBuffer>?
395
+ guard CVPixelBufferCreateWithIOSurface(nil, surface, nil, &source) == kCVReturnSuccess, let source else { return }
396
+ let input = source.takeRetainedValue()
397
+ var output: CVPixelBuffer?
398
+ guard CVPixelBufferPoolCreatePixelBuffer(nil, pool, &output) == kCVReturnSuccess, let output else { return }
399
+ guard VTPixelTransferSessionTransferImage(transfer, from: input, to: output) == noErr else { return }
400
+ let time = CMTime(value: frames, timescale: CMTimeScale(fps))
401
+ frames += 1
402
+ let options = forceKey ? [kVTEncodeFrameOptionKey_ForceKeyFrame: kCFBooleanTrue] as CFDictionary : nil
403
+ forceKey = false
404
+ VTCompressionSessionEncodeFrame(session, imageBuffer: output, presentationTimeStamp: time, duration: .invalid,
405
+ frameProperties: options, infoFlagsOut: nil) { status, _, sample in
406
+ guard status == noErr, let sample else { return }
407
+ Encoder.write(sample)
408
+ }
409
+ }
410
+
411
+ /// One access unit as Annex-B, then the next unit's AUD: the reader splits at AUDs, so the unit is complete now.
412
+ static func write(_ sample: CMSampleBuffer) {
413
+ guard let block = CMSampleBufferGetDataBuffer(sample), let format = CMSampleBufferGetFormatDescription(sample) else { return }
414
+ let attachments = CMSampleBufferGetSampleAttachmentsArray(sample, createIfNecessary: false) as? [[CFString: Any]]
415
+ let key = !((attachments?.first?[kCMSampleAttachmentKey_NotSync] as? Bool) ?? false)
416
+ var unit = Data()
417
+ if key {
418
+ var count = 0
419
+ CMVideoFormatDescriptionGetH264ParameterSetAtIndex(format, parameterSetIndex: 0, parameterSetPointerOut: nil,
420
+ parameterSetSizeOut: nil, parameterSetCountOut: &count, nalUnitHeaderLengthOut: nil)
421
+ for index in 0..<count {
422
+ var pointer: UnsafePointer<UInt8>?
423
+ var length = 0
424
+ CMVideoFormatDescriptionGetH264ParameterSetAtIndex(format, parameterSetIndex: index, parameterSetPointerOut: &pointer,
425
+ parameterSetSizeOut: &length, parameterSetCountOut: nil, nalUnitHeaderLengthOut: nil)
426
+ guard let pointer, length > 0 else { continue }
427
+ let set = Data(bytes: pointer, count: length)
428
+ unit.append(startCode)
429
+ unit.append(set[set.startIndex] & 0x1F == 7 ? lowDelaySps(set) : set)
430
+ }
431
+ }
432
+ var total = 0
433
+ var base: UnsafeMutablePointer<CChar>?
434
+ guard CMBlockBufferGetDataPointer(block, atOffset: 0, lengthAtOffsetOut: nil, totalLengthOut: &total, dataPointerOut: &base) == noErr,
435
+ let base else { return }
436
+ var offset = 0
437
+ while offset + 4 <= total {
438
+ var length: UInt32 = 0
439
+ memcpy(&length, base.advanced(by: offset), 4)
440
+ let nal = Int(CFSwapInt32BigToHost(length))
441
+ offset += 4
442
+ guard offset + nal <= total else { break }
443
+ unit.append(startCode)
444
+ base.advanced(by: offset).withMemoryRebound(to: UInt8.self, capacity: nal) { unit.append($0, count: nal) }
445
+ offset += nal
446
+ }
447
+ unit.append(accessUnitDelimiter)
448
+ writeOut(unit)
449
+ }
450
+ }
451
+
452
+ @MainActor
453
+ func stream(_ udid: String, fps: Int, maxPixels: Double, kbps: Int) async {
454
+ let target: FBSimulator
455
+ let framebuffer: FBFramebuffer
456
+ do {
457
+ target = try await simulator(udid)
458
+ framebuffer = try FBFramebuffer.mainScreenSurface(for: target, logger: logger)
459
+ } catch {
460
+ fail("connect_failed: \\(error.localizedDescription)")
461
+ }
462
+ let encoder = Encoder(fps: fps, maxPixels: maxPixels, kbps: kbps)
463
+ let first = framebuffer.attach(encoder, on: encoder.queue)
464
+ encoder.queue.async { if let first, encoder.surface == nil { encoder.surface = first } }
465
+ writeOut(accessUnitDelimiter)
466
+ let timer = DispatchSource.makeTimerSource(queue: encoder.queue)
467
+ timer.schedule(deadline: .now(), repeating: .nanoseconds(1_000_000_000 / max(1, fps)))
468
+ timer.setEventHandler { encoder.tick() }
469
+ timer.resume()
470
+ // "key" on stdin asks for a keyframe; end of stdin ends the stream.
471
+ do {
472
+ for try await line in FileHandle.standardInput.bytes.lines where line == "key" {
473
+ encoder.queue.async { encoder.forceKey = true; encoder.dirty = true }
474
+ }
475
+ } catch {}
476
+ framebuffer.detach(encoder)
477
+ _ = target
478
+ exit(0)
479
+ }
480
+
481
+ // MARK: - main
482
+
483
+ signal(SIGPIPE, SIG_IGN)
484
+ let arguments = CommandLine.arguments
485
+ guard arguments.count >= 3 else { fail("usage: simulator-host serve|stream <udid> ...") }
486
+ switch arguments[1] {
487
+ case "serve":
488
+ await serve(arguments[2])
489
+ case "stream":
490
+ guard arguments.count == 6, let fps = Int(arguments[3]), let maxPixels = Double(arguments[4]), let kbps = Int(arguments[5]) else {
491
+ fail("usage: simulator-host stream <udid> <fps> <max pixels> <kbps>")
492
+ }
493
+ await stream(arguments[2], fps: fps, maxPixels: maxPixels, kbps: kbps)
494
+ default:
495
+ fail("usage: simulator-host serve|stream <udid> ...")
496
+ }
497
+ `;var J5=process.arch==="arm64"?"arm64-apple-macos":"x86_64-apple-macos",RJ=180000,qJ=15000,gJ=30000,EJ=600000,kJ=["SimDevice","SimDeviceSet","SimDeviceType","SimRuntime"].map(($)=>`@interface ${$} : NSObject
498
+ @end
499
+ `).join("");function Z5($,J,Z){return new Promise((Q)=>{let K=e2($,J,{stdio:["ignore","pipe","pipe"],timeout:Z}),B="";K.stdout.on("data",(V)=>{B+=V}),K.stderr.on("data",(V)=>{B+=V}),K.once("error",(V)=>Q({code:-1,output:String(V)})),K.once("close",(V)=>Q({code:V??-1,output:B}))})}var Q5=new Map;function $3($){let J=k(K5($),"Frameworks"),Z=Q5.get(J);if(!Z)Q5.set(J,Z=SJ(J));return Z}async function SJ($){if(process.platform!=="darwin"||!o2(k($,"FBSimulatorControl.framework")))return null;let J=await Z5("xcrun",["swiftc","--version"],30000);if(J.code!==0)return null;let Z=OJ("sha256").update(i2).update(J.output).update($).digest("hex").slice(0,16),Q=k(PJ(),".local","share","reason","simulator","host"),K=k(Q,Z,"simulator-host");if(o2(K))return K;d1(Q,{recursive:!0,mode:448});let B=AJ(k(Q,".staging-"));try{let V=k(B,"Frameworks"),U=k(V,"FBSimulatorControl.framework"),z=k(U,"Modules","FBSimulatorControl.swiftmodule");d1(z,{recursive:!0});for(let L of t8($))if(L!=="FBSimulatorControl.framework")t2(k($,L),k(V,L));let W=k($,"FBSimulatorControl.framework");t2(k(W,"FBSimulatorControl"),k(U,"FBSimulatorControl")),t2(k(W,"Headers"),k(U,"Headers")),J1(k(U,"Modules","module.modulemap"),e8(k(W,"Modules","module.modulemap")));let G=e8(k(W,"Modules","FBSimulatorControl.swiftmodule",`${J5}.swiftinterface`),"utf8");J1(k(z,`${J5}.swiftinterface`),G.replace(/FBSimulatorControl\.(?=[A-Za-z_])/g,"").replace(/IOSurface\.IOSurface/g,"IOSurface"));let F=k(B,"include","CoreSimulator");d1(F,{recursive:!0}),J1(k(F,"module.modulemap"),`module CoreSimulator {
500
+ header "CoreSimulator.h"
501
+ export *
502
+ }
503
+ `),J1(k(F,"CoreSimulator.h"),`#import <Foundation/Foundation.h>
504
+ ${kJ}`);let Y=k(B,"main.swift");J1(Y,i2);let N=k(B,"simulator-host"),C=await Z5("xcrun",["swiftc","-O","-F",V,"-I",k(B,"include"),"-module-cache-path",k(B,"cache"),"-Xlinker","-rpath","-Xlinker",$,Y,"-o",N],RJ);if(C.code!==0||!o2(N))return process.stderr.write(`Reason: the simulator host did not build; simulator actions use AXe.
505
+ ${C.output.slice(-2000)}
506
+ `),null;d1(K5(K),{recursive:!0}),_J(N,K);for(let L of t8(Q))if(L!==Z&&!L.startsWith(".staging-"))$5(k(Q,L),{recursive:!0,force:!0});return K}catch{return null}finally{$5(B,{recursive:!0,force:!0})}}class Z1 extends Error{}class E0 extends Error{}class B5{child;onGone;nextId=1;pending=new Map;idle;gone=!1;constructor($,J){this.child=$;this.onGone=J;TJ({input:$.stdout}).on("line",(Q)=>{let K;try{K=JSON.parse(Q)}catch{return}let B=this.pending.get(Number(K.id));if(!B)return;if(this.pending.delete(Number(K.id)),clearTimeout(B.timer),K.ok===!0)B.resolve(K);else B.reject(new Z1(String(K.error??"The simulator refused the action.")))}),$.once("exit",()=>this.end()),$.once("error",()=>this.end()),this.touch()}call($){if(this.gone)return Promise.reject(new E0("The simulator host has exited."));this.touch();let J=this.nextId++;return new Promise((Z,Q)=>{let K=setTimeout(()=>{this.pending.delete(J),Q(new E0("The simulator host did not answer.")),this.close()},gJ);this.pending.set(J,{resolve:Z,reject:Q,timer:K}),this.child.stdin.write(`${JSON.stringify({id:J,...$})}
507
+ `)})}close(){if(this.child.exitCode===null&&this.child.signalCode===null)this.child.kill("SIGTERM");this.end()}touch(){clearTimeout(this.idle),this.idle=setTimeout(()=>this.close(),EJ),this.idle.unref?.()}end(){if(this.gone)return;this.gone=!0,clearTimeout(this.idle);for(let $ of this.pending.values())clearTimeout($.timer),$.reject(new E0("The simulator host has exited."));this.pending.clear(),this.onGone()}}var g0=new Map;async function l1($,J,Z=!1){let Q=g0.get(J);if(!Q){let K={started:bJ($,J)};g0.set(J,Q=K),K.started.then((B)=>{if(K.host=B,!B&&g0.get(J)===K)g0.delete(J)})}if(Q.host!==void 0)return Q.host;return Z?Q.started:null}async function bJ($,J){let Z=await $3($);if(!Z)return null;let Q=e2(Z,["serve",J],{stdio:["pipe","pipe","ignore"]});if(!await new Promise((V)=>{let U=setTimeout(()=>V(!1),qJ);Q.stdout.once("data",(z)=>{clearTimeout(U),V(String(z).includes('"ready":true'))}),Q.once("exit",()=>{clearTimeout(U),V(!1)}),Q.once("error",()=>{clearTimeout(U),V(!1)})})){if(Q.exitCode===null)Q.kill("SIGTERM");return null}let B=new B5(Q,()=>{let V=g0.get(J);if(V&&(V.host===B||V.host===void 0))g0.delete(J)});return B}function V5($,J,Z,Q,K){return e2($,["stream",J,String(Z),String(Math.round(Q)),String(K)],{stdio:["pipe","pipe","ignore"]})}var k0={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"},mJ=50000,vJ=112640,uJ=174080,J3=2,pJ=60000,dJ=2000,lJ=300,sJ=40,cJ=new Set(["file:","javascript:","data:","vbscript:","blob:"]);function f0($,J,Z={}){return new Promise((Q,K)=>{let B=W3($,J,{cwd:Z.cwd,stdio:["ignore","pipe","pipe"],signal:Z.signal}),V=[],U=[];B.stdout.on("data",(W)=>V.push(W)),B.stderr.on("data",(W)=>U.push(W));let z=setTimeout(()=>B.kill("SIGKILL"),Z.timeoutMs??mJ);B.on("error",(W)=>{clearTimeout(z),K(W)}),B.on("close",(W)=>{clearTimeout(z),Q({code:W??-1,stdout:Buffer.concat(V).toString("utf8"),stderr:Buffer.concat(U).toString("utf8")})})})}function E($,J){throw new H($,J)}async function l($,J,Z,Q={}){let K=await f0($,J,Q);if(K.code!==0)E("simulator_command_failed",`${Z} failed: ${(K.stderr||K.stdout).trim().slice(-1500)}`);return K.stdout}function K1(){return process.platform==="darwin"&&J0("/Library/Developer/PrivateFrameworks/CoreSimulator.framework")&&J0("/usr/bin/xcrun")}var Z3=null;function I0(){return q(Y3(),".local","share","reason","simulator","axe")}function N3(){let $=q(I0(),k0.version,"axe");if(J0($))return Promise.resolve($);return Z3??=(async()=>{B3(I0(),{recursive:!0,mode:448});let J=z3(q(I0(),".staging-"));try{let Z=q(J,"axe.tgz");await T5(k0.url,k0.sha256,Z);let Q=q(J,"tree");if(B3(Q),await l("tar",["-xzf",Z,"-C",Q],"Extracting AXe"),!J0(q(Q,"axe"))||!J0(q(Q,"Frameworks")))E("simulator_axe_missing","The AXe archive has an unexpected layout.");Q1(q(I0(),k0.version),{recursive:!0,force:!0}),yJ(Q,q(I0(),k0.version));for(let K of a1(I0()))if(K!==k0.version&&!K.startsWith(".staging-"))Q1(q(I0(),K),{recursive:!0,force:!0});return $}finally{Q1(J,{recursive:!0,force:!0}),Z3=null}})(),Z3}var D5=N3;async function j5($){let J=await N3().catch(()=>null);return J?l1(J,$.udid).catch(()=>null):null}async function c1($,J,Z){let Q=await N3().catch(()=>E("simulator_axe_missing","AXe could not be installed on this Mac.")),K=await f0(Q,[...$,"--udid",J]);if(K.code===0)return K.stdout;let B=(K.stderr||K.stdout).trim();if(/no (matching |accessibility )?element|element not found|could not find|no elements? match/i.test(B))E("simulator_element_not_found",B.slice(-500));return E("simulator_command_failed",`${Z} failed: ${B.slice(-1500)}`)}function nJ($){let J=$.match(/SimRuntime\.([A-Za-z]+)-(\d+)-(\d+)(?:-(\d+))?$/);return J?`${J[1]} ${J[2]}.${J[3]}${J[4]?`.${J[4]}`:""}`:$}function rJ($){switch($){case"Booted":return"booted";case"Booting":return"booting";case"Shutting Down":return"shutting_down";default:return"shutdown"}}async function H3(){let J=JSON.parse(await l("xcrun",["simctl","list","devices","available","-j"],"Listing simulators")).devices??{},Z=[];for(let[Q,K]of Object.entries(J)){if(!Q.includes("SimRuntime.iOS"))continue;for(let B of K){if(B.isAvailable===!1)continue;let V=B.name.toLowerCase();if(B.deviceTypeIdentifier)U3.set(B.udid,B.deviceTypeIdentifier);Z.push({udid:B.udid,name:B.name,runtime:nJ(Q),state:rJ(B.state),kind:V.includes("iphone")?"iphone":V.includes("ipad")?"ipad":"other"})}}return Z.sort((Q,K)=>Number(K.state==="booted")-Number(Q.state==="booted")||K.runtime.localeCompare(Q.runtime,void 0,{numeric:!0})||Q.name.localeCompare(K.name))}var U3=new Map,X3=null;async function a($,J){let Z=await H3(),Q;if($){let K=Z.filter((B)=>B.udid===$||B.name===$);if(Q=K.find((B)=>B.state==="booted")??K[0],!Q)E("simulator_device_not_found",`No simulator named "${$}". Call devices to list them.`)}else{let K=Z.filter((B)=>B.state==="booted");if(Q=K.find((B)=>B.udid===X3)??K.find((B)=>B.kind==="iphone")??K[0],!Q)E("simulator_not_booted","No simulator is booted. Call devices, then boot one.")}if(J.booted&&Q.state!=="booted")E("simulator_not_booted",`${Q.name} is not booted. Boot it first.`);return X3=Q.udid,Q}function y($){return`${$.name} (${$.runtime})`}async function aJ($){if($.state!=="booted"){let J=await f0("xcrun",["simctl","boot",$.udid]);if(J.code!==0&&!/current state: Booted/i.test(J.stderr))E("simulator_command_failed",`Booting ${$.name} failed: ${J.stderr.trim().slice(-1000)}`);await l("xcrun",["simctl","bootstatus",$.udid,"-b"],`Waiting for ${$.name} to boot`,{timeoutMs:45000})}return X3=$.udid,{...$,state:"booted"}}function C3($,J){let Z=G3($,J),Q=C5($,Z);if(Q.startsWith("..")||Q.startsWith(w5)||G3($,Q)!==Z)E("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 G5=4,iJ=new Set(["node_modules","Pods","DerivedData","build","Carthage","vendor"]);function oJ($){let J=[],Z=(Q,K)=>{let B;try{B=a1(Q)}catch{return}if(B.includes("project.yml")||B.some((V)=>V.endsWith(".xcworkspace")||V.endsWith(".xcodeproj"))){J.push(Q);return}if(K>=G5)return;for(let V of B.sort()){if(V.startsWith(".")||iJ.has(V))continue;let U=q(Q,V);try{if(s1(U).isDirectory())Z(U,K+1)}catch{}}};if(Z($,0),J.length===1)return J[0];if(!J.length)E("simulator_project_not_found",`No Xcode project or project.yml within ${G5} folders of ${$}; pass path.`);return E("simulator_project_not_found",`${$} holds several Xcode projects; pass path as one of: ${J.map((Q)=>C5($,Q)||".").join(", ")}.`)}var b0=new Map;async function tJ($){if($.endsWith(".xcworkspace"))return{flag:"-workspace",path:$,dir:V3($)};if($.endsWith(".xcodeproj"))return{flag:"-project",path:$,dir:V3($)};if(!s1($).isDirectory())E("simulator_project_not_found",`${$} is not a project, workspace or folder.`);let J=(K)=>a1($).filter((B)=>B.endsWith(K)).sort();if(J0(q($,"project.yml")))await l("xcodegen",["generate","--quiet"],"xcodegen generate",{cwd:$,timeoutMs:45000}).catch((K)=>J0("/opt/homebrew/bin/xcodegen")?l("/opt/homebrew/bin/xcodegen",["generate","--quiet"],"xcodegen generate",{cwd:$,timeoutMs:45000}):Promise.reject(K));let Z=J(".xcworkspace")[0];if(Z)return{flag:"-workspace",path:q($,Z),dir:$};let Q=J(".xcodeproj")[0];if(Q)return{flag:"-project",path:q($,Q),dir:$};return E("simulator_project_not_found",`No .xcodeproj or .xcworkspace in ${$}.`)}async function M5($){let J=JSON.parse(await l("xcodebuild",["-list","-json",$.flag,$.path],"Listing schemes"));return J.workspace?.schemes??J.project?.schemes??[]}async function eJ($){let J=(await M5($))[0];if(!J)E("simulator_build_no_scheme",`${$.path} has no schemes; pass scheme.`);return J}function $Z($){let J=[],Z=new Set;return $.forEach((Q,K)=>{if(J.length>=20||!/(^|\s)error: /.test(Q)||Q.startsWith("note:")||Z.has(Q))return;Z.add(Q);let B=$.slice(K+1,K+3).filter((V)=>V.trim()!==""&&!/(^|\s)(error|warning|note): /.test(V));J.push([Q,...B].join(`
508
+ `).slice(0,800))}),J}async function JZ($,J,Z){if($.ended=Date.now(),J!==0){if($.log.some((B)=>B.includes("does not contain a scheme named"))){let B=await M5(Z).catch(()=>[]);if(B.length)$.log.push(`error: this project's schemes are: ${B.join(", ")}`)}$.status="failed";return}let Q=q($.productsDir,`${$.configuration}-iphonesimulator`),K=J0(Q)?a1(Q).filter((B)=>B.endsWith(".app")).map((B)=>q(Q,B)).sort((B,V)=>s1(V).mtimeMs-s1(B).mtimeMs):[];if($.appPath=K[0],$.appPath)$.bundleId=await O5($.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 U5($,J){let Z=$.path?C3(J,$.path):oJ(J),Q=await tJ(Z),K=$.scheme??await eJ(Q),B=$.configuration??"Debug",V=await a($.device,{booted:!1}).catch(()=>null),U=V?`platform=iOS Simulator,id=${V.udid}`:"generic/platform=iOS Simulator",z=fJ("sha256").update(Q.path).digest("hex").slice(0,16),W=q(Y3(),"Library","Caches","reason","simulator-builds",z),G={id:`build-${xJ().slice(0,8)}`,status:"running",started:Date.now(),log:[],productsDir:q(W,"Build","Products"),configuration:B};b0.set(G.id,G);for(let[C,L]of b0)if(b0.size>20&&L.status!=="running")b0.delete(C);let F=W3("xcodebuild",[Q.flag,Q.path,"-scheme",K,"-configuration",B,"-destination",U,"-derivedDataPath",W,"-skipMacroValidation","build"],{cwd:Q.dir,stdio:["ignore","pipe","pipe"]}),Y="",N=(C)=>{let L=(Y+C.toString("utf8")).split(`
509
+ `);if(Y=L.pop()??"",G.log.push(...L),G.log.length>5000)G.log.splice(0,G.log.length-5000)};return F.stdout.on("data",N),F.stderr.on("data",N),F.on("error",(C)=>{G.log.push(`error: ${C.message}`),G.status="failed",G.ended=Date.now()}),F.on("close",(C)=>{if(Y)G.log.push(Y);JZ(G,C??-1,Q)}),{text:`Build ${G.id} started: ${K} (${B}) for ${V?y(V):"the iOS Simulator"}. Poll build_status with this build_id; a first build can take minutes, later ones are incremental.`,build:L5(G)}}function L5($){return{id:$.id,status:$.status,errors:$Z($.log),log_tail:$.log.slice(-sJ).join(`
510
+ `).slice(-4000),elapsed_ms:($.ended??Date.now())-$.started,...$.appPath?{app_path:$.appPath}:{},...$.bundleId?{bundle_id:$.bundleId}:{}}}var ZZ=45000,QZ=30000;async function Q3($,J=ZZ){let Z=Date.now()+J;while(b0.get($)?.status==="running"&&Date.now()<Z)await Bun.sleep(500);let Q=I5($);return Q.build?.status==="running"?{...Q,text:`${Q.text} Still running: call build_status with wait again.`}:Q}function I5($){let J=b0.get($);if(!J)E("simulator_build_not_found",`No build ${$} on this Mac (a worker restart forgets builds); start a new one.`);let Z=L5(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 O5($){return(await l("plutil",["-extract","CFBundleIdentifier","raw","-o","-",q($,"Info.plist")],"Reading the bundle id")).trim()}var H0=new Map;function KZ($,J){H0.get($.udid)?.stop();let Z=W3("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")};H0.set($.udid,Q);let K="",B=(V)=>{let U=(K+V.toString("utf8").replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\r]/g,"")).split(`
511
+ `);K=U.pop()??"",Q.lines.push(...U);let z=Q.lines.length-dJ;if(z>0)Q.lines.splice(0,z),Q.first+=z};return Z.stdout.on("data",B),Z.stderr.on("data",B),new Promise((V)=>{let U=setTimeout(()=>V(null),15000),z=()=>{let W=Q.lines.concat(K).join(`
512
+ `).match(new RegExp(`${J.replace(/\./g,"\\.")}: (\\d+)`))?.[1];if(W)clearTimeout(U),V(Number(W))};Z.stdout.on("data",z),Z.on("close",()=>{clearTimeout(U),V(null)})})}async function BZ($,J){let Z=await a($.device,{booted:!0}),Q=$.bundle_id;if($.app_path){let B=VZ(J,$.app_path);await l("xcrun",["simctl","install",Z.udid,B],`Installing ${H5(B)}`),Q=await O5(B)}if($.bundle_id){if((await f0("xcrun",["simctl","get_app_container",Z.udid,$.bundle_id])).code!==0)E("simulator_app_not_installed",`${$.bundle_id} is not installed on ${y(Z)}.`)}let K=await KZ(Z,Q);if(K===null){let B=H0.get(Z.udid)?.lines.slice(-20).join(`
513
+ `)??"";E("simulator_launch_failed",`${Q} did not start on ${y(Z)}.${B?`
514
+ ${B}`:""}`)}return{text:`Launched ${Q} on ${y(Z)} (pid ${K}). Its console is captured; read it with logs.`,device:Z}}function VZ($,J){let Z=G3(J),Q=q(Y3(),"Library","Caches","reason","simulator-builds")+w5;return Z.startsWith(Q)&&Z.endsWith(".app")?Z:C3($,Z)}function GZ($,J){let Z=H0.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-lJ),K=Z.lines.slice(Q-Z.first).map((B)=>B.slice(0,2000));return{text:`${K.length} console line(s) from ${Z.bundleId} on ${y($)}.`,logs:{lines:K,next:Z.first+Z.lines.length}}}var n1=new Map;function X5($,...J){let Z=n1.get($.udid);if(!Z)return;for(let[Q,K]of J)if(Q>Z.width||K>Z.height)E("simulator_point_off_screen",`(${Q}, ${K}) is off ${$.name}'s ${Z.width}x${Z.height}-point screen.`)}function W5($,J){if($.kind==="ipad")return 2;return J===750||J===828||J===640?2:3}async function w3($,J=1,Z){let Q=z3(q(N5(),"reason-sim-"));try{let K=q(Q,"screen.png");if(await l("xcrun",["simctl","io",$.udid,"screenshot","--type=png",K],"Taking a screenshot"),Z){B3(V3(Z),{recursive:!0});let N=await l("sips",["-g","pixelWidth","-g","pixelHeight",K],"Reading the screenshot size"),C=Number(N.match(/pixelWidth: (\d+)/)?.[1]),L=Number(N.match(/pixelHeight: (\d+)/)?.[1]),D=2/W5($,C);await l("sips",["-z",String(Math.round(L*D)),String(Math.round(C*D)),K,"--out",Z],"Saving the screenshot")}let B=await l("sips",["-g","pixelWidth","-g","pixelHeight",K],"Reading the screenshot size"),V=Number(B.match(/pixelWidth: (\d+)/)?.[1]),U=Number(B.match(/pixelHeight: (\d+)/)?.[1]),z=W5($,V),W=Math.round(V/z),G=Math.round(U/z);n1.set($.udid,{width:W,height:G});let F=Buffer.alloc(0),Y=J===2?uJ:vJ;for(let N of[70,50,35]){let C=q(Q,`screen-${N}.jpg`);if(await l("sips",["-z",String(G*J),String(W*J),"-s","format","jpeg","-s","formatOptions",String(N),K,"--out",C],"Encoding the screenshot"),F=F3(C),F.byteLength<=Y)break}return{text:`Screenshot of ${y($)} at ${W}x${G} points: image pixels are tap coordinates.`+(Z?` Saved at ${Z}.`:""),device:$,image:{mime:"image/jpeg",data:F.toString("base64"),width:W,height:G}}}finally{Q1(Q,{recursive:!0,force:!0})}}async function UZ($){let J=await j5($);if(J)try{return String((await J.call({op:"tree"})).tree)}catch{}return c1(["describe-ui"],$.udid,"Reading the accessibility tree")}async function r1($){let J=JSON.parse(await UZ($)),Z={lines:[],compact:[],ids:new Set,labels:new Set,targets:[]},Q=(K,B,V="")=>{let U=(K.role??K.type??"?").replace(/^AX/,""),z=K.AXLabel||K.title||"",W=K.AXValue?` value="${String(K.AXValue).slice(0,120)}"`:"",G=K.AXUniqueId?` id=${K.AXUniqueId}`:"";if(K.AXUniqueId)Z.ids.add(K.AXUniqueId);if(z)Z.labels.add(z);let F=K.frame;if(U==="Application"&&F&&!Z.bounds)Z.bounds={width:F.width,height:F.height};if(F&&F.width>0&&F.height>0&&(K.AXUniqueId||K.AXLabel))Z.targets.push({...K.AXUniqueId?{id:K.AXUniqueId.trim()}:{},...K.AXLabel?{label:K.AXLabel.trim()}:{},role:U,frame:F});let Y=Boolean(z||G||W||!["Group","Other"].includes(U));if(Y){let N=`${" ".repeat(Math.min(B,12))}${U} "${z.slice(0,160)}"${G}${W}`+(F?` (${Math.round(F.x)},${Math.round(F.y)} ${Math.round(F.width)}x${Math.round(F.height)})`:"")+(K.enabled===!1?" disabled":"");Z.lines.push(N);let C=U==="Image"&&!G,L=(U==="StaticText"||U==="Image")&&!G&&z!==""&&V.includes(z);if(!C&&!L)Z.compact.push(N)}for(let N of K.children??[])Q(N,Y?B+1:B,z||V)};for(let K of J)Q(K,0);return Z}function A5($,J,Z=!1){let Q=(Z?$.compact:$.lines).join(`
515
+ `);return Q.length>J?`${Q.slice(0,J)}
516
+ \u2026 (truncated)`:Q}async function XZ($){let J=await r1($);return{text:`Accessibility tree of ${y($)} (frames in points; tap by id or label):
517
+ ${A5(J,pJ)}`,device:$}}var WZ=450,zZ=1e4;function FZ($,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 K=null,B="";if(J.wait_for){let U=Date.now()+(J.timeout??5)*1000,z=J.wait_for,W=z.id?`id ${z.id}`:`"${z.label}"`;for(;;){if(K=await r1($),FZ(K,z)){B=` ${W} is ${z.gone?"gone":"on screen"}.`;break}if(Date.now()>=U){B=z.gone?` Waited ${J.timeout??5} s: ${W} is still on screen.`:` Waited ${J.timeout??5} s: ${W} is not in the visible accessibility tree. Lists only build their visible rows, so check the screen below: it may be open with that element further down (scroll to it), or wait for something at its top.`;break}await Bun.sleep(250)}}else await Bun.sleep(WZ);let V={...Z,text:`${Z.text}${B}`};if(Q==="tree"||Q==="both")K??=await r1($),V.screen=A5(K,zZ,!0),V.text+=`
518
+ Screen now:
519
+ ${V.screen}`;if(Q==="screenshot"||Q==="both"){let U=await w3($);V.image=U.image}return V}function z5($){return`'${$.replace(/'/g,"'\\''")}'`}function YZ($){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 ${z5($.id)}`:`tap --label ${z5($.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 _5=0.35,NZ=new Set(["Button","Link","Cell","MenuItem","Switch","Toggle","CheckBox","PopUpButton","TextField","SecureTextField","SearchField","TextArea","Slider","Tab","RadioButton"]);function HZ($,J){let Z=$.targets.filter((W)=>J.id!==void 0?W.id===J.id.trim():W.label===J.label?.trim()),Q=(W)=>({x:W.frame.x+W.frame.width/2,y:W.frame.y+W.frame.height/2}),K=$.bounds,B=K?Z.filter((W)=>{let{x:G,y:F}=Q(W);return G>=0&&F>=0&&G<=K.width&&F<=K.height}):Z,V=B.length?B:Z,U=V.filter((W)=>NZ.has(W.role)),z=(U.length?U:V)[0];return z?Q(z):null}async function CZ($,J,Z,Q,K){let B=Date.now()+Z*1000;for(;;){let V=HZ(await r1($),J);if(V)return V;if(Date.now()>=B){let U=J.id!==void 0?`--id '${J.id}'`:`--label '${J.label}'`;return E("simulator_element_not_found",`Error: Step ${Q} failed: [tap]
520
+ No accessibility element matched ${U}. Make sure the app is on the expected screen, then inspect it and prefer an id when there is one.
521
+ (${Q-1} of ${K} steps had completed.)`)}await Bun.sleep(250)}}async function S0($,J,Z){let Q=await j5($);if(!Q)return F5($,J,Z);for(let[K,B]of J.entries()){try{switch(B.action){case"tap":{let U=B.x!==void 0&&B.y!==void 0?{x:B.x,y:B.y}:await CZ($,B,Z,K+1,J.length);await Q.call(B.duration?{op:"tap",...U,duration:B.duration}:{op:"tap",...U});break}case"swipe":await Q.call({op:"swipe",x:B.x,y:B.y,x2:B.x2,y2:B.y2,duration:B.duration??0.3});break;case"button":await Q.call({op:"button",name:B.name});break;case"type":await Q.call({op:"text",text:B.text}).catch((U)=>U instanceof Z1?c1(["type",B.text],$.udid,`Step ${K+1} (typing)`):Promise.reject(U));break;case"sleep":await Bun.sleep(B.seconds*1000);break}}catch(U){if(U instanceof E0)return await F5($,J.slice(K),Z),`Ran ${J.length} step(s) on ${y($)}.`;if(U instanceof Z1)E("simulator_command_failed",`Step ${K+1} failed: ${U.message}
522
+ (${K} of ${J.length} steps had completed.)`);throw U}let V=J[K+1];if(B.action!=="sleep"&&V&&V.action!=="sleep")await Bun.sleep(_5*1000)}return`Ran ${J.length} step(s) on ${y($)}.`}async function F5($,J,Z){let Q=[],K=[],B=0,V=0,U=async()=>{if(Q.length===0)return;let z=["batch","--ax-cache","perStep","--wait-timeout",String(Z)];for(let W of Q)z.push("--step",W);try{await c1(z,$.udid,`Steps ${V+1}-${V+B}`)}catch(W){if(W instanceof H){let G=W.message.replace(/Step (\d+) failed/,(F,Y)=>{let N=K[Number(Y)-1];return N?`Step ${N} failed`:F});E(W.code,`${G}
523
+ (${V} of ${J.length} steps had completed before this batch.)`)}throw W}V+=B,Q=[],K=[],B=0};for(let[z,W]of J.entries()){if(W.action==="type"){await U(),await c1(["type",W.text],$.udid,`Step ${V+1} (typing)`),V+=1;continue}Q.push(YZ(W)),B+=1,K.push(z+1);let G=J[z+1];if(W.action!=="sleep"&&G&&G.action!=="sleep")Q.push(`sleep ${_5}`),K.push(z+1)}return await U(),`Ran ${J.length} step(s) on ${y($)}.`}var wZ=["topLeft","top","topRight","right","bottomRight","bottom","bottomLeft","left"],Y5=new Map,DZ=`ObjC.import("AppKit");
524
+ function run(argv) {
525
+ const [input, output, width, height] = argv;
526
+ const w = Number(width), h = Number(height);
527
+ const image = $.NSImage.alloc.initWithContentsOfFile(input);
528
+ const rep = $.NSBitmapImageRep.alloc.initWithBitmapDataPlanesPixelsWidePixelsHighBitsPerSampleSamplesPerPixelHasAlphaIsPlanarColorSpaceNameBytesPerRowBitsPerPixel(
529
+ null, w, h, 8, 4, true, false, $.NSDeviceRGBColorSpace, 0, 0);
530
+ $.NSGraphicsContext.saveGraphicsState;
531
+ $.NSGraphicsContext.setCurrentContext($.NSGraphicsContext.graphicsContextWithBitmapImageRep(rep));
532
+ image.drawInRectFromRectOperationFraction($.NSMakeRect(0, 0, w, h), $.NSZeroRect, $.NSCompositingOperationCopy, 1);
533
+ $.NSGraphicsContext.restoreGraphicsState;
534
+ rep.representationUsingTypeProperties($.NSBitmapImageFileTypePNG, $()).writeToFileAtomically(output, true);
535
+ }`;async function K3($,J,Z){let Q=await l("sips",["-g","pixelWidth","-g","pixelHeight",$],"Reading the frame size"),K=Number(Q.match(/pixelWidth: ([\d.]+)/)?.[1]),B=Number(Q.match(/pixelHeight: ([\d.]+)/)?.[1]);if(Z!==void 0)K=K*Z/B,B=Z;let V=z3(q(N5(),"reason-chrome-"));try{let U=q(V,"render.js"),z=q(V,"out.png");if(hJ(U,DZ),await l("osascript",["-l","JavaScript",U,$,z,String(Math.max(1,Math.round(K*J))),String(Math.max(1,Math.round(B*J)))],"Rendering the frame"),!J0(z))E("simulator_command_failed",`Rendering ${H5($)} produced no image.`);return{image:F3(z).toString("base64"),width:K,height:B}}finally{Q1(V,{recursive:!0,force:!0})}}async function jZ($){if(!U3.has($.udid))await H3();let J=U3.get($.udid),Q=JSON.parse(await l("xcrun",["simctl","list","devicetypes","-j"],"Listing device types")).devicetypes?.find((K)=>K.identifier===J)?.bundlePath;if(!Q)E("simulator_command_failed",`No device type bundle for ${$.name}.`);return Q}async function MZ($){let J=await jZ($),Z=n1.get($.udid)??($.state==="booted"?(await w3($),n1.get($.udid)):void 0);if(!Z)E("simulator_not_booted",`${$.name} is not booted.`);let Q=Y5.get(J);if(Q)return{text:`Frame of ${y($)}.`,device:$,chrome:Q};let K=q(J,"Contents","Resources"),B=JSON.parse(await l("plutil",["-convert","json","-o","-",q(K,"profile.plist")],"Reading the device profile")),V=B.framebufferMask?q(K,`${B.framebufferMask}.pdf`):null,U=V&&J0(V)?await K3(V,J3,Z.height):null,z=B.chromeIdentifier?.split(".").pop(),W=z?q("/Library/Developer/DeviceKit/Chrome",`${z}.devicechrome`,"Contents","Resources"):"";if(!z||!J0(q(W,"chrome.json")))E("simulator_command_failed",`${$.name} has no device frame in this Xcode.`);let G=JSON.parse(F3(q(W,"chrome.json"),"utf8")),F={};for(let M of wZ){let I=G.images[M];if(!I)E("simulator_command_failed",`${$.name}'s frame has no ${M} piece.`);F[M]=await K3(q(W,`${I}.pdf`),J3)}let{sizing:Y}=G.images,N={top:Y.topHeight,left:Y.leftWidth,bottom:Y.bottomHeight,right:Y.rightWidth},C=Z.width+N.left+N.right,L=Z.height+N.top+N.bottom,D=[];for(let M of G.inputs??[]){let I=q(W,`${M.image}.pdf`);if(!J0(I))continue;let A=await K3(I,J3),{x:S,y:v}=M.offsets.normal,s=(C0,m,z1)=>C0<0?m+C0-z1:C0,z0=M.anchor==="left"?{x:S-A.width,y:s(v,L,A.height)}:M.anchor==="right"?{x:C+S,y:s(v,L,A.height)}:M.anchor==="top"?{x:s(S,C,A.width),y:v-A.height}:{x:s(S,C,A.width),y:L+v};D.push({name:M.name,image:A.image,...z0,width:A.width,height:A.height})}let w={identifier:G.identifier,screen:{width:Z.width,height:Z.height},inset:N,padding:G.images.devicePadding??{top:0,left:0,bottom:0,right:0},pieces:F,buttons:D,...U?{screen_mask:U.image}:{}};return Y5.set(J,w),{text:`Frame of ${y($)}.`,device:$,chrome:w}}var LZ=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 B1($){try{return await P5($)}catch(J){if(J instanceof H&&LZ.has(J.code))return{text:J.message,error:J.code};throw J}}async function P5($){if(!K1())E("simulator_xcode_missing","Xcode's iOS Simulator is not available on this Mac.");let J=a2.safeParse($.payload);if(!J.success)E("simulator_invalid_request",J.error.issues.map((Q)=>Q.message).join("; "));let Z=J.data;switch(Z.action){case"devices":{let Q=await H3(),K=Q.filter((B)=>B.state==="booted");return{text:`${K.length} booted (${K.map(y).join(", ")||"none"}), ${Q.length} available.`,devices:Q}}case"boot":{let Q=await aJ(await a(Z.device,{booted:!1}));return{text:`${y(Q)} is booted.`,device:Q}}case"shutdown":{let Q=await a(Z.device,{booted:!1});H0.get(Q.udid)?.stop(),H0.delete(Q.udid);let K=await f0("xcrun",["simctl","shutdown",Q.udid]);if(K.code!==0&&!/current state: Shutdown/i.test(K.stderr))E("simulator_command_failed",K.stderr.trim().slice(-1000));return{text:`${y(Q)} is shut down.`,device:{...Q,state:"shutdown"}}}case"build":{let Q=await U5(Z,$.root);return Z.wait&&Q.build?Q3(Q.build.id):Q}case"build_status":return Z.wait?Q3(Z.build_id):I5(Z.build_id);case"run":{let Q=await U5({...Z,action:"build"},$.root),K=await Q3(Q.build.id,QZ);if(K.build?.status!=="succeeded"||!K.build.app_path)return K;let B=await P5({root:$.root,payload:{action:"launch",app_path:K.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{...B,text:`Built in ${Math.round(K.build.elapsed_ms/1000)} s. ${B.text}`,build:K.build}}case"launch":{let Q=await BZ(Z,$.root);if(!Q.device)return Q;if(Z.steps?.length)Q.text+=` ${await S0(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 a(Z.device,{booted:!0});return O0(Q,Z,{text:await S0(Q,Z.steps,Z.timeout??5),device:Q})}case"terminate":{let Q=await a(Z.device,{booted:!0});if(H0.get(Q.udid)?.bundleId===Z.bundle_id)H0.get(Q.udid)?.stop();return await f0("xcrun",["simctl","terminate",Q.udid,Z.bundle_id]),{text:`Terminated ${Z.bundle_id} on ${y(Q)}.`,device:Q}}case"logs":return GZ(await a(Z.device,{booted:!1}),Z.after);case"screenshot":return w3(await a(Z.device,{booted:!0}),Z.scale,Z.save_path?C3($.root,Z.save_path):void 0);case"chrome":return MZ(await a(Z.device,{booted:!1}));case"inspect":return XZ(await a(Z.device,{booted:!0}));case"tap":{let Q=await a(Z.device,{booted:!0}),K=Z.x!==void 0&&Z.y!==void 0;if(K)X5(Q,[Z.x,Z.y]);await S0(Q,[K?{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 B=K?`(${Z.x}, ${Z.y})`:Z.id?`id ${Z.id}`:`"${Z.label}"`;return O0(Q,Z,{text:`Tapped ${B} on ${y(Q)}.`,device:Q})}case"swipe":{let Q=await a(Z.device,{booted:!0});return X5(Q,[Z.x,Z.y],[Z.x2,Z.y2]),await S0(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 a(Z.device,{booted:!0});return await S0(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 a(Z.device,{booted:!0});return await S0(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 a(Z.device,{booted:!0}),K;try{K=new URL(Z.url)}catch{E("simulator_invalid_request","open_url needs an absolute URL.")}if(cJ.has(K.protocol))E("simulator_invalid_request",`${K.protocol} URLs are not allowed.`);return await l("xcrun",["simctl","openurl",Q.udid,K.href],"Opening the URL"),O0(Q,Z,{text:`Opened ${K.href} on ${y(Q)}.`,device:Q})}case"appearance":{let Q=await a(Z.device,{booted:!0});return await l("xcrun",["simctl","ui",Q.udid,"appearance",Z.mode],"Setting the appearance"),{text:`${y(Q)} is in ${Z.mode} mode.`,device:Q}}}}import{mkdtempSync as IZ,readFileSync as OZ,rmSync as AZ}from"fs";import{tmpdir as _Z}from"os";import{join as R5}from"path";import{spawn as k5}from"child_process";var PZ=/^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/i,V1=1,TZ=[{bit:8,dx:0,dy:1},{bit:16,dx:0,dy:-1},{bit:32,dx:1,dy:0},{bit:64,dx:-1,dy:0}],q5=60,RZ=8,S5=K1;var g5={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},qZ=(()=>{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,K]of J)$[Z]=K,$[Q]=K;return $})();function gZ($){if(g5[$]!==void 0)return g5[$];return $>=32&&$<=126?qZ[String.fromCharCode($)]??null:null}function b5($,J){let Z=k5("xcrun",["simctl","pbcopy",$],{stdio:["pipe","ignore","ignore"]});Z.once("error",()=>{}),Z.stdin.end(J)}function EZ($,J){let Z=0,Q={x:0,y:0},K=(B)=>{J.call(B).catch(()=>{})};return{pointer(B,V,U){let z=(U&V1)!==0;if(z&&!(Z&V1))K({op:"touch",phase:"down",x:B,y:V});else if(z&&(B!==Q.x||V!==Q.y))K({op:"touch",phase:"move",x:B,y:V});else if(!z&&Z&V1)K({op:"touch",phase:"up",x:B,y:V});for(let W of TZ)if(U&W.bit&&!(Z&W.bit))K({op:"swipe",x:B,y:V,x2:B+W.dx*q5,y2:V+W.dy*q5,duration:0.08});Z=U,Q={x:B,y:V}},key(B,V){let U=gZ(V);if(U!==null)K({op:"key",usage:U,down:B})},clipboard(B){b5($,B)},close(){if(Z&V1)K({op:"touch",phase:"up",...Q});Z=0}}}function kZ($,J){let Z=null,Q="",K,B=(V)=>{B1({payload:{...V,device:$,observe:"none"},root:J}).catch(()=>{})};return{pointer(V,U,z){let W=(z&V1)!==0;if(W&&!Z)Z={x:V,y:U,at:Date.now()};if(!W&&Z){let G=(Date.now()-Z.at)/1000;if(Math.hypot(V-Z.x,U-Z.y)>RZ)B({action:"swipe",x:Z.x,y:Z.y,x2:V,y2:U,duration:Math.min(Math.max(G,0.05),1)});else B({action:"tap",x:Z.x,y:Z.y,...G>0.5?{duration:Math.min(G,10)}:{}});Z=null}},key(V,U){if(!V)return;let z=U===65293?`
536
+ `:U>=32&&U<=126?String.fromCharCode(U):null;if(z===null)return;Q+=z,clearTimeout(K),K=setTimeout(()=>{let W=Q;Q="",B({action:"type",text:W})},250)},clipboard(V){b5($,V)},close(){clearTimeout(K),Z=null}}}function SZ($,J,Z){return new Promise((Q,K)=>{let B=k5($,J,{stdio:"ignore",signal:Z});B.once("error",K),B.once("exit",(V)=>Q(V??-1))})}async function bZ($,J){let Z=IZ(R5(_Z(),"reason-simulator-stream-"));try{let Q=R5(Z,"screen.png");if(await SZ("xcrun",["simctl","io",$,"screenshot","--type=png",Q],J)!==0)throw new H("simulator_not_booted","That simulator is not booted.");let K=OZ(Q).subarray(16,24);return{width:K.readUInt32BE(0),height:K.readUInt32BE(4)}}finally{AZ(Z,{recursive:!0,force:!0})}}async function f5($,J={}){let{udid:Z,...Q}=$.payload;if(typeof Z!=="string"||!PZ.test(Z)||!Q.video)throw new H("invalid_display_request","Reason simulator stream request is malformed.");let K=await D5().catch(()=>{throw new H("simulator_axe_missing","AXe could not be installed on this Mac.")}),B=await B1({payload:{action:"screenshot",device:Z},root:$.root});if(B.error||!B.image)throw new H("simulator_not_booted","That simulator is not booted.");let V={width:B.image.width,height:B.image.height},U=await $3(K),z=U?await l1(K,Z,!0):null,W=U?null:await E5();if(!U&&!W)throw new H("display_video_unsupported","This Mac can build neither the simulator host nor find an H.264 ffmpeg.");let G={kind:"simulator",udid:Z,axe:K,points:V,sound:null,size:U?V:await bZ(Z,$.signal),stream:U?(F,Y,N)=>V5(U,Z,Math.min(F,60),N,Y):null,input:z?EZ(Z,z):kZ(Z,$.root)};return await i1({payload:Q,signal:$.signal},{...J,video:{desktop:async()=>G,...W?{ffmpeg:()=>W}:{}}})}var O7=131072,cZ=131072,nZ=128,A7=8192,S3=30000,b3=15000,rZ=/^[a-z][a-z0-9_]{0,63}$/,aZ=new Set(["jobs.control","fs.read","fs.write"]),x5=new Set(["cancelled","run_finished","run_cancelled","driver_handoff","driver_stopped"]);function o1($){return $.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/[a-z]/gi,(J)=>`[${J.toLowerCase()}${J.toUpperCase()}]`)}function y5($){return $.map(o1).join("/")}function D3($,J){let Z=[];for(let Q=0;Q<$.length;Q+=J)Z.push($.slice(Q,Q+J));return Z}var iZ=[...D3(C1,4).map(($)=>`/(${$.map(y5).join("|")})(/|$)`),...D3(w1,4).map(($)=>`/(${$.map(y5).join("|")})$`),...D3([...D1],6).map(($)=>`/(${$.map(o1).join("|")})$`),`/${o1(".env")}\\.[^/]+$`,`/[^/]+(${j1.map(o1).join("|")})$`],T3=new Set(["add","am","apply","branch","checkout","cherry-pick","clean","commit","merge","mv","rebase","remote","reset","restore","revert","rm","stash","switch","tag"]),_7=new Set(["blame","diff","for-each-ref","grep","log","ls-files","rev-list","rev-parse","shortlog","show","status"]);function P7($){return[$.requiredPermission,...$.additionalPermissions??[]]}function oZ($){return f6($)}function R3(){if(R()==="darwin")return G0("/usr/bin/sandbox-exec");if(R()==="linux"||R()==="win32")return y6();return!1}function h5(){if(R()==="linux")return G0("/proc");if(R()==="win32")return u6()!==null;if(!R3())return!1;if(R()==="darwin")return G0("/usr/sbin/lsof");return!1}function T7(){return R()==="darwin"?"/bin/zsh":h6()}function q3($){return Boolean($)&&typeof $==="object"&&!Array.isArray($)}function tZ($){if(!q3($))throw new H("invalid_payload","Operation payload must be an object.");if(Buffer.byteLength(JSON.stringify($),"utf8")>Y0)throw new H("payload_too_large","Operation payload exceeds 256 KB.");return $}function v0($,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 J2($,J,Z=A7){let Q=v0($,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 eZ($,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 X1($,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 A0($,J){if(R()==="win32")[$,J]=[$.toLowerCase(),J.toLowerCase()];return J===$||J.startsWith(`${$}${lZ}`)}function y0($){if(R6($))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=B0($.path)}catch(Z){if(process.platform==="darwin"&&Z7(Z))throw Q7($.path);throw new H("root_unavailable","The granted root is unavailable.")}if(J!==$.path||!W1(J).isDirectory())throw new H("root_changed","The granted root changed after registration.");return y0(J),J}function f3($,J="."){if(!J||J.includes("\x00")||pZ(J))throw new H("path_outside_root","Paths must be relative to the granted root.");if(R()==="win32"&&J.split(/[\\/]/).some(k1))throw new H("invalid_path","Windows reserves this file name.");let Z=dZ($,J);if(!A0($,Z))throw new H("path_outside_root","Path escapes the granted root.");return Z}function m0($,J=".",Z=!1){let Q=f3($,J),K;try{K=B0(Q)}catch(B){if(E7(B))throw k7();throw new H("path_not_found","Path does not exist.")}if(!A0($,K))throw new H("symlink_escape","Path resolves outside the granted root.");if(!Z)y0(K);return K}function $Q($,J){let Z=f3($,J);if(y0(Z),G0(Z)){let B=B0(Z);if(!A0($,B))throw new H("symlink_escape","Write target resolves outside the granted root.");if(_3(Z).isSymbolicLink())throw new H("symlink_escape","Writing through a symlink is not allowed.");return y0(B),B}let Q=U1(Z);while(!G0(Q)){let B=U1(Q);if(B===Q)throw new H("path_outside_root","No safe write parent.");Q=B}let K=B0(Q);if(!A0($,K))throw new H("symlink_escape","Write parent resolves outside the granted root.");return y0(K),Z}function R7($,J){return P3($,J)||"."}function JQ($,J=O7){let Z=Buffer.from($,"utf8");if(Z.byteLength<=J)return{value:$,truncated:!1};return{value:Z.subarray(0,J).toString("utf8"),truncated:!0}}function q7($,J){return{...x6({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 ZQ($,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($)}))`]:[],...iZ.map((K)=>`(deny file-read* file-write* (regex #"${K}"))`),...q6($,Z),"(deny network*)"].join(`
537
+ `)}async function x3($,J,Z){return new Promise((Q,K)=>{let B="",V="",U=!1,z=!1,W=!1,G;try{G=sZ($,J,{cwd:Z.cwd,env:Z.env,shell:!1,stdio:["ignore","pipe","pipe"],...g6()}),E6(G)}catch(L){K(L);return}let F=(L,D)=>{if(W)return;W=!0,clearTimeout(C),Z.signal.removeEventListener("abort",N),Q({exitCode:L,signal:D,stdout:B,stderr:V,timedOut:z,truncated:U})},Y=(L,D)=>{let w=`${L}${String(D)}`,M=JQ(w);return U||=M.truncated,M.value};G.stdout.on("data",(L)=>{B=Y(B,L)}),G.stderr.on("data",(L)=>{V=Y(V,L)}),G.once("error",K),G.once("exit",F);let N=()=>{try{if(R()==="win32"&&G.pid)k6(G.pid);else G.kill("SIGTERM")}catch{}};Z.signal.addEventListener("abort",N,{once:!0});let C=setTimeout(()=>{z=!0,N()},Z.timeoutMs)})}var m5=null;function QQ(){return m5??=m6({scrubEnvironment:q7,spawnCaptured:x3,isProtectedPath:R0}),m5}var KQ=async($,J,Z)=>{if(R()==="linux"||R()==="win32")return QQ()($,J,Z);if(R()!=="darwin"||!G0("/usr/bin/sandbox-exec"))throw new H("sandbox_unavailable","Confined command execution is unavailable on this operating system.");let Q=yZ(I7(uZ(),"reason-device-"));try{return await x3("/usr/bin/sandbox-exec",["-p",ZQ(Z.root,Q,Z.allowWrite,Z.allowProcessInspection===!0),$,...J],{cwd:Z.cwd,timeoutMs:Z.timeoutMs,signal:Z.signal,env:q7(Z.root,Q)})}finally{mZ(Q,{recursive:!0,force:!0})}};function BQ($){let J=$.args;if(J===void 0)return[];if(!Array.isArray(J)||J.length>nZ)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")>A7)throw new H("invalid_payload","Command argument is invalid or too large.");return Z})}async function g7($,J,Z,Q={}){if($.signal.aborted)throw new H("cancelled","Operation was cancelled.");let K=h($.root),B=Q.cwd??K,V=await $.runCommand(J,Z,{cwd:B,root:K,allowWrite:Q.allowWrite===!0,timeoutMs:Q.timeoutMs??b3,signal:$.signal});if(V.exitCode!==0&&/permission denied|operation not permitted|EACCES|EPERM/i.test(V.stderr))await $.emit("permission.denied",{operation:"bash",provenance:$.worker?.executionMode==="unsandboxed"?"os_permission_unknown":"sandbox_policy"});return{exit_code:V.exitCode,signal:V.signal,stdout:V.stdout,stderr:V.stderr,timed_out:V.timedOut,truncated:V.truncated}}function E7($){let J=$ instanceof Error&&"code"in $?$.code:null;return J==="EACCES"||J==="EPERM"}var k7=()=>new H("path_unreadable","The path is not readable.");function VQ($){try{return L7($,Z0.O_RDONLY)}catch(J){throw E7(J)?k7():J}}function v5($,J){let Z=h0()?e1():null;return Z?$2(Z,{op:"fs",capability:$,root:J.root,payload:J.payload},J.signal).then((Q)=>Q.value):GQ($,J)}function GQ($,J){return $==="fs.read"?UQ(J):WQ(J)}async function UQ($){let J=h($.root),Z=m0(J,J2($.payload,"path"));if(!W1(Z).isFile())throw new H("not_a_file","Read target is not a file.");let Q=X1($.payload.offset,0,0,Number.MAX_SAFE_INTEGER),K=X1($.payload.max_bytes,65536,1,O7),B=v0($.payload,"encoding");if(B!==void 0&&B!=="base64")throw new H("invalid_payload","encoding must be base64.");let V=VQ(Z),U,z;try{U=M7(V).size;let G=Buffer.alloc(Math.max(0,Math.min(K,U-Q)));z=G.subarray(0,G.byteLength?hZ(V,G,0,G.byteLength,Q):0)}finally{j7(V)}let W=B==="base64"||z.includes(0);return{path:R7(J,Z),content:W?z.toString("base64"):z.toString("utf8"),encoding:W?"base64":"utf8",offset:Q,bytes:z.byteLength,size:U,truncated:Q+z.byteLength<U}}function XQ($,J,Z=R()){let Q=$==="append"?Z0.O_APPEND:Z0.O_TRUNC;if(Z==="win32")return J?Z0.O_WRONLY|($==="append"?Z0.O_APPEND:0):Z0.O_WRONLY|Z0.O_CREAT|Z0.O_EXCL;return Z0.O_WRONLY|Z0.O_NOFOLLOW|Q|(J?0:Z0.O_CREAT|Z0.O_EXCL)}async function WQ($){let J=h($.root),Z=J2($.payload,"path"),Q=eZ($.payload,"content",cZ),K=v0($.payload,"mode")??"overwrite";if(!["create","overwrite","append"].includes(K))throw new H("invalid_payload","mode must be create, overwrite, or append.");let B=$Q(J,Z);if($.payload.create_parents===!0||$.payload.create_directories===!0){xZ(U1(B),{recursive:!0,mode:448});let W=B0(U1(B));if(!A0(J,W))throw new H("symlink_escape","Write parent escaped root.")}if(!G0(U1(B)))throw new H("path_not_found","Write parent does not exist.");if(K==="create"&&G0(B))throw new H("path_exists","Create mode will not overwrite an existing file.");let V=G0(B),U=V?_3(B):null,z=L7(B,XQ(K,V),384);try{let W=M7(z),G=U??(R()==="win32"?_3(B):null);if(G&&(W.ino!==G.ino||W.dev!==G.dev||R()==="win32"&&!A0(J,B0(B))))throw new H("symlink_escape","The write target changed between validation and opening.");if(R()==="win32"&&U&&K!=="append")fZ(z,0);vZ(z,Q,null,"utf8")}finally{j7(z)}return{path:R7(J,B),bytes_written:Buffer.byteLength(Q,"utf8"),mode:K}}async function zQ($){let J=h($.root),Z=J2($.payload,"command",65536),Q=m0(J,v0($.payload,"cwd")??".");if(!W1(Q).isDirectory())throw new H("invalid_cwd","cwd is not a directory.");let K=X1($.payload.timeout_ms,b3,100,S3);return g7($,T7(),["-lc",Z],{cwd:Q,allowWrite:$.root.permissions.write,timeoutMs:K})}async function FQ($){let J=z7.safeParse($.payload),Z=$.worker;if(!J.success||!$.claimOwner||(Z?!Z.runtimeDirectory:R()!=="darwin"))throw new H("preview_unavailable","Preview servers are unavailable on this computer.");let Q=h($.root),K=j6(Q,J.data.workspace),B=K.boundary===Q?Q:m0(K.anchor,P3(K.anchor,K.boundary)||"."),V=m0(B,P3(B,K.path)||".");if(!W1(V).isDirectory())throw new H("invalid_cwd","The Session checkout is not a directory.");let U=Math.min(Date.parse(J.data.expires_at),Date.now()+U7);if(!(U>Date.now()))throw new H("process_authority_lost","The preview server lease is unavailable.");let z=(w)=>$.emit("progress",{process:w});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 A3({claim:$.claim,root:B,cwd:V,command:J.data.command,mode:"host",shell:q0(),environment:process.env,expiresAtMs:U,signal:$.signal,emit:z})}}let W={directory:I7(Z.runtimeDirectory,"processes")},G={deniedPorts:l6([$.apiOrigin])},F=$7(),Y=J7(),N=h0(),C=J.data.egress?t1(N):null;if(J.data.egress&&(C===null||!x0(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 L=J.data.egress?await j4(J.data.egress.allowed_domains):null,D=L?[`export ${["HTTP_PROXY","HTTPS_PROXY","http_proxy","https_proxy"].map((w)=>`${w}=${L.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(`
538
+ `):J.data.command;try{return{...await A3({claim:$.claim,root:V,cwd:V,command:D,mode:"host",shell:Y,expiresAtMs:U,signal:$.signal,emit:z,...N?{jobsUser:{...N,...C!==null?{modelGid:C}:{}}}:{},environment:{...F.variables,HOME:F.home,PATH:F.path,TMPDIR:F.temporaryDirectory,SHELL:Y},journals:W,preview:G})}}finally{L?.close()}}async function YQ($){y2();let J=h($.root),Z=h2($.payload.command),Q=m0(J,v0($.payload,"cwd")??".");if(!W1(Q).isDirectory())throw new H("invalid_cwd","cwd is not a directory.");let K=X1($.payload.timeout_ms,j8,100,f2),{ignored:B}=m2($.payload.env);return await $.emit("progress",{shell:q0(),shell_flags:[...e0],sandbox:"none",ignored_env:B}),L8({command:Z,cwd:Q,timeoutMs:K,signal:$.signal,spawn:$.spawnFullControl,requestEnv:$.payload.env})}async function NQ($){let J=h($.root),Z=BQ($.payload),Q=Z[0];if(!Q||!_7.has(Q)&&!T3.has(Q))throw new H("git_command_not_allowed","Git subcommand is not in the Device allowlist.");if(Z.some((V)=>V==="-C"||V==="-c"||V.startsWith("--git-dir")||V.startsWith("--work-tree")||V.startsWith("--config-env")||V.startsWith("--exec-path")))throw new H("git_argument_not_allowed","Git path/config overrides are not allowed.");let K=T3.has(Q);if(K&&!$.root.permissions.write)throw new H("permission_denied","Mutating Git commands require the write grant.");let B=m0(J,v0($.payload,"cwd")??".");return g7($,"git",["-c","core.hooksPath=/dev/null","-c","credential.helper=",...Z],{cwd:B,allowWrite:K||process.platform==="win32"&&$.root.permissions.write,timeoutMs:X1($.payload.timeout_ms,b3,100,S3)})}function S7($,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 HQ($){let J=h($.root);if(R()==="linux")return E8(J);if(R()==="win32")return p6(J);return x8(J,S7($,J))}async function CQ($){let J=h($.root);if(R()==="linux")return k8(J);if(R()==="win32")return d6(J);return y8(J,S7($,J))}async function wQ($){let J=$.worker?c8($.worker):null,Z=$.claim.environment;delete $.claim.environment;let Q=$.worker&&Z&&y3({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:(K,B,V)=>$.emit(K,B,V)})}async function DQ($){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}=s6($.payload,$.operationId);return a6({root:h($.root),runId:$.runId,deviceId:$.deviceId,rootId:$.root.id,workspace:J,session:Z,owner:$.claimOwner,authority:$.claimAuthority,signal:$.signal,emit:(Q,K)=>$.emit(Q,K)})}return $.runPtySession({root:h($.root),runId:$.runId,operationId:$.operationId,payload:$.payload,signal:$.signal,emitEvent:(J,Z)=>$.emit(J,Z)})}function u5($,J){let Z=h0()?e1():null;return Z?$2(Z,{op:"transfer",direction:J,root:$.root,payload:$.payload,worker:Boolean($.worker)},$.signal).then((Q)=>Q.value):jQ(J,{root:$.root,payload:$.payload,signal:$.signal,worker:Boolean($.worker),fetchImpl:$.fetchImpl,beforeCommit:()=>$.emit("progress",{phase:"file_transfer_verified"})})}async function jQ($,J){let Z=h(J.root),Q=a0 in J.payload;if(Q&&!J.worker)throw new H("cloud_copy_workspace_invalid","Only a worker resolves a Cloud copy workspace.");let K=Q?c4(Z,J.payload[a0]):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 U=g4.safeParse(J.payload);if(!U.success)throw new H("invalid_payload","Invalid Cloud export request.");return n4({runtimeRoot:K,source:U.data.source,url:U.data.url,signal:J.signal,fetchImpl:J.fetchImpl})}let B=J2(J.payload,"path",4096),V=$==="import"&&Q?g2(K):K;return y0(f3(V,B)),T0({direction:$,root:V,path:B,payload:J.payload,signal:J.signal,fetchImpl:J.fetchImpl,beforeCommit:J.beforeCommit})}var b7={"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 a3({payload:$.payload,signal:$.signal,credential:$.customEndpointCredential,emit:(J,Z)=>$.emit(J,Z,$.signal)})}},"fs.read":{requiredPermission:"read",execute:($)=>v5("fs.read",$)},"fs.write":{requiredPermission:"write",execute:($)=>v5("fs.write",$)},"fs.export":{requiredPermission:"read",execute:($)=>u5($,"export")},"fs.import":{requiredPermission:"write",execute:($)=>u5($,"import")},"preview.serve.v1":{requiredPermission:"execute",additionalPermissions:["discover_environment"],available:()=>R()==="darwin"&&x2(),execute:FQ},"exec.run":{requiredPermission:"execute",available:R3,execute:zQ},"exec.full":{requiredPermission:"execute",additionalPermissions:["discover_environment"],available:()=>x2(),execute:YQ},"git.run":{requiredPermission:"execute",available:()=>R3()&&oZ("git"),execute:NQ},"process.list":{requiredPermission:"read",additionalPermissions:["discover_environment"],available:h5,execute:HQ},"ports.list":{requiredPermission:"read",additionalPermissions:["discover_environment"],available:h5,execute:CQ},"hands.connect":{requiredPermission:"execute",additionalPermissions:["read","write","discover_environment"],available:()=>R()==="darwin"||Boolean(K7()),execute:wQ},"pty.start":{requiredPermission:"execute",additionalPermissions:["discover_environment"],available:C7,execute:DQ},"display.stream.v1":{requiredPermission:"execute",additionalPermissions:["discover_environment"],available:D7,execute:($)=>{let J=e1();return J?$2(J,{op:"display",payload:$.payload,proxy:($.relay.loadProxy??S6)()},$.signal):i1({payload:$.payload,signal:$.signal},$.relay)}},"automation.call.v1":{requiredPermission:"execute",additionalPermissions:["read","discover_environment"],available:()=>f7(),execute:($)=>x7({runId:$.runId,payload:$.payload,signal:$.signal,...$.worker?.userChrome?{userChrome:$.worker.userChrome}:{}})},"simulator.call.v1":{requiredPermission:"execute",additionalPermissions:["read","discover_environment"],available:K1,execute:($)=>B1({payload:$.payload,root:h($.root)})},"simulator.stream.v1":{requiredPermission:"execute",additionalPermissions:["read","discover_environment"],available:S5,execute:($)=>f5({payload:$.payload,root:h($.root),signal:$.signal},$.relay)},"jobs.control":{requiredPermission:"execute",additionalPermissions:["read","write","discover_environment"],available:()=>!0,execute:($)=>i6({root:h($.root),runId:$.runId,payload:$.payload,signal:$.signal})},"github.local.v1":{requiredPermission:"read",additionalPermissions:["execute","discover_environment"],available:()=>R()==="darwin"?G0("/usr/bin/sandbox-exec"):R()==="linux"||R()==="win32",execute:async($)=>{let J=I1.parse($.payload),Z=E3.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||!D0(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 o6({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($)=>k3({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:($)=>n6({root:h($.root),runId:$.runId,owner:$.claimOwner,payload:$.payload,signal:$.signal})},"tunnel.close":{requiredPermission:"execute",additionalPermissions:["read","write","discover_environment"],execute:($)=>r6({root:h($.root),runId:$.runId,owner:$.claimOwner,payload:$.payload,signal:$.signal})},"workspace.setup.v1":{requiredPermission:"execute",additionalPermissions:["read","write"],available:R2,execute:($)=>u4($.payload,$.signal)}};function MQ($,J){try{let Z=o3($,B0(J)),Q=Z?$.find((K)=>K.path===Z):void 0;return Q&&/^[a-f0-9]{64}$/.test(Q.pathFingerprint)?Q.pathFingerprint:void 0}catch{return}}function LQ($,J){try{let Z=B0(J);return $.some((Q)=>Q.path===Z)?N1(Z,R()):void 0}catch{return}}function IQ($,J){try{let Z=B0(J),Q=$.find((K)=>K.path===Z);return Q&&/^[a-f0-9]{64}$/.test(Q.pathFingerprint)?Q.pathFingerprint:void 0}catch{return}}function OQ($,J){try{let Z=B0(J);if(!$.some((Q)=>Q.path===Z))return;return $.filter((Q)=>Q.path!==Z&&A0(Z,Q.path)&&/^[a-f0-9]{64}$/.test(Q.pathFingerprint)).map((Q)=>Q.pathFingerprint)}catch{return}}function AQ($,J,Z=R()){try{return H1({home:N1(B0(J),Z),roots:$.map((Q)=>({path_fingerprint:Q.pathFingerprint,path:N1(Q.path,Z)})).filter((Q)=>/^[a-f0-9]{64}$/.test(Q.path_fingerprint)&&Y1(Q.path)).slice(0,B2)})}catch{return}}function DG($,J={}){let Z=J.worker?J.worker.handsSlots??1:J.handsSlots===1?1:void 0,Q=Boolean(J.worker)||R()==="darwin",K=Q?IQ($,G1()):void 0,B=!J.worker&&R()==="darwin"?MQ($,G1()):void 0,V=Q?LQ($,G1()):void 0,U=!J.worker&&R()==="darwin"?OQ($,G1()):void 0,z=Q?AQ($,G1()):void 0,W=b2.filter((G)=>{if(t0.has(G)&&!J.worker)return!1;if(J.worker&&!y1(G,J.worker))return!1;let F=b7[G];if(!F)return!1;return(G==="hands.connect"&&(J.terminalOnlyHands===!0||Boolean(J.worker))||(G==="pty.start"||G==="preview.serve.v1")&&Boolean(J.worker)||G==="browser.pr-proof.v1"&&Boolean(J.productionProof)?!0:F.available?.()??!0)&&$.some((N)=>(!J.worker||G!=="pty.start"||N.permissions.read&&N.permissions.write)&&P7(F).every((C)=>N.permissions[C]))});return{supported_operations:W,...K?{account_root_fingerprint:K}:{},...B?{workspace_root_fingerprint:B}:{},...V?{account_root_path:V}:{},...U?{home_contained_root_fingerprints:U}:{},...z?{root_paths:z}:{},...W.includes("hands.connect")?{hands_worker_artifact_sha256:O3,hands_worker_entrypoint:I3,...Z?{hands_slots:Z}:{}}:{},max_payload_bytes:Y0,max_result_bytes:Y0,operation_constraints:{...W.includes("browser.pr-proof.v1")&&J.productionProof?{"browser.pr-proof.v1":F2.parse(J.productionProof)}:{},...W.includes("exec.run")?{"exec.run":{transport:"shell",shell:T7(),sandbox:R()==="linux"?"linux_sandbox_runtime":R()==="win32"?"windows_srt":"macos_seatbelt",network:!1,max_timeout_ms:S3}}:{},...W.includes("exec.full")?{"exec.full":I8()}:{},"git.run":{read_only_subcommands:[..._7].sort(),mutating_subcommands:[...T3].sort(),push:!1,credential_helpers:!1},"fs.export":{transport:"https_signed_url",max_bytes:X0,max_timeout_ms:r0,result:"sha256_and_size"},"fs.import":{transport:"https_signed_url",max_bytes:X0,max_timeout_ms:r0,atomic:!0,overwrite:!1},"hands.connect":{transport:"wss_relay",worker:"ara_hands",worker_version:L3,protocol_version:M3,worker_artifact_sha256:O3,worker_entrypoint:I3,policy_mode:"full_access",policy_version:1,workspace_base:j3,workspace_layout:o0,...Z?{slots:Z}:{},browser_state:J.worker?"optional_headless":J.terminalOnlyHands===!0?"disabled_terminal_only":R()==="darwin"?"optional_isolated_per_session":"isolated_per_session",max_session_ms:43200000},...W.includes("pty.start")?{"pty.start":{transport:"wss_relay",shell:"login_shell",resize:!0,slots:H7,max_session_ms:Y7,max_buffered_output_bytes:N7}}:{},...J.worker?Object.fromEntries(W.filter((G)=>G!=="browser.pr-proof.v1").map((G)=>[G,{ready:J.worker?.readiness?.[G]===!0,...J.worker?.readiness?.[G]!==!0&&J.worker?.probing?.includes(G)?{probing:!0}:{},execution_mode:y1(G,{...J.worker,executionMode:"sandboxed"})?"confined":"host",...G==="pty.start"?{transport:"wss_relay",worker:"ara_hands",shell:"bound_job",protocol_version:v6,environment:"private_snapshot",receipt:"metadata_only",...J.worker?.persistentTerminals&&!h0()?{persistent_terminals:!0}:{}}:{},...G==="github.local.v1"?{contributor_attribution:2,prepare_diagnostics:1,...J.worker?.githubSignedIn!==void 0?{gh_authenticated:J.worker.githubSignedIn}:{}}:{},...G==="hands.connect"?{transport:"wss_relay",worker:"ara_hands",slots:Z,session_group:z6,...J.worker?.ownComputer?{[F6]:Y6}:{},workspace_base:j3,workspace_layout:o0,browser_state:"optional_headless",desktop:!1,worker_version:L3,protocol_version:M3,...J.worker?.readiness?.["environment.install"]===!0&&W.includes("environment.install")?{environment_delivery:l5,[n5]:c5}:{},...J.worker?{[o5]:i5}:{},...J.worker?{[a5]:r5}:{},...J.worker?.handsBrowser?{[Z6]:J6}:{},[$6]:e5,[K6]:Q6,...x0(J.worker?.executionMode==="unsandboxed")?{[V6]:B6}:{},...x0(J.worker?.executionMode==="unsandboxed")&&t1()!==null?{[U6]:G6}:{},...x0(J.worker?.executionMode==="unsandboxed")&&h0()?{[W6]:X6}:{}}:{},...G==="fs.export"?{cloud_source_version:T1,source_kinds:["workspace","attachment"],[w2]:D2}:{},...G==="fs.import"?{[w2]:D2}:{},...G===G7&&t1()!==null&&x0(J.worker?.executionMode==="unsandboxed")?{[W7]:X7}:{},...G==="tunnel.open"?{carried_jobs:N6}:{},...G==="jobs.control"?{[C6]:H6}:{},...G==="display.stream.v1"&&J.worker?.displayVideo?{[L6]:M6,[O6]:I6.join(","),[A6]:_6,[P6]:T6}:{},...G==="automation.call.v1"&&J.worker?.userChrome?{[w6]:!0}:{},...G==="automation.call.v1"&&J.worker?.cloudSessions?{[D6]:!0}:{}}])):{}}}}function y3($,J,Z,Q,K){let B=e6.safeParse(Q);return B.success&&K!==void 0&&K.device_id===$.deviceId&&B.data.device_id===$.deviceId&&B.data.root_id===J&&B.data.run_id===Z&&B.data.binding.kind===K.binding&&B.data.binding.target_revision===K.target_revision&&B.data.binding.root_grant_revision===K.root_grant_revision&&B.data.binding.target_generation===K.target_generation&&B.data.binding.target_fence_id===K.target_fence_id}async function jG($,J,Z,Q,K){if(J.capability!=="hands.connect"||Z.kind!==s5||!Q.operationEnvironment||!Q.acknowledgeOperationEnvironment)return!1;let B=Z.payload.snapshot_id;if(Z.payload.version!==1||typeof B!=="string"||Object.keys(Z.payload).length!==2)throw new H("environment_unavailable","Reason sent an invalid environment delivery.");let V=$.roots.find((W)=>W.id===J.root_id);if(!V)throw new H("root_not_granted","The Hands root is no longer granted.");let U=await Q.operationEnvironment($,J,B,K);if(!y3($,V.id,J.run_id,U.payload,U.authority)||U.payload.snapshot_id!==B)throw new H("environment_unavailable","The delivered environment does not match this Hands.");let z=k3({root:h(V),operationId:J.operation_id,payload:U.payload});return await Q.acknowledgeOperationEnvironment($,J,{snapshot_id:z.snapshot_id,installed_revision:z.installed_revision,installed:!0},K),!0}async function MG($,J,Z,Q){if(J.capability!=="hands.connect"||Z.kind!==t5)return!1;let{version:K,run_id:B,target_generation:V,target_fence_id:U}=Z.payload;if(K!==1||Object.keys(Z.payload).length!==4||typeof B!=="string"||typeof V!=="number"||typeof U!=="string")throw new H("hands_rebind_unavailable","Reason sent an invalid Hands rebind.");let z=$.roots.find((W)=>W.id===J.root_id);if(!z)throw new H("root_not_granted","The Hands root is no longer granted.");return await c6({operationId:J.operation_id,root:h(z),runId:B,targetGeneration:V,fenceId:U,...Q?{signal:Q}:{}}),!0}async function LG($,J,Z){if(J.capability!=="github.local.v1")return p5($,J,Z);try{let Q=await p5($,J,Z);if(Q.status==="succeeded"||g3(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 p5($,J,Z){if(t0.has(J.capability)&&!Z.worker)return{status:"failed",error_code:"capability_not_granted"};if(Z.worker&&!y1(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 G=E3.safeParse(J.local_github_authority);if(!G.success||G.data.deviceId!==$.deviceId||G.data.rootId!==J.root_id||G.data.runId!==J.run_id||G.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=b7[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 K=$.roots.find((G)=>G.id===J.root_id);if(!K)return{status:"failed",error_code:"root_not_granted"};if((J.capability==="fs.export"||J.capability==="fs.import")&&q3(J.payload)&&(("source"in J.payload)||("source_version"in J.payload))){let G=Boolean(Z.worker||$.worker)&&a0 in J.payload;if(J.capability!=="fs.export"||!G)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"&&!y3($,K.id,J.run_id,J.payload,J.authority))return{status:"failed",error_code:"environment_unavailable"};if(P7(Q).some((G)=>!K.permissions[G]))return{status:"failed",error_code:"permission_denied"};let B=0,V=async(G,F,Y)=>{if(["environment.install","github.local.v1"].includes(J.capability)||J.capability==="inference.custom.v1"&&(G==="started"||G==="completed"))return;await Z.emit?.({sequence:B++,kind:G,capability:J.capability,data:F,...(G==="hands.reconnected"||J.capability==="inference.custom.v1")&&Y?{deliverySignal:Y}:{}})},U=J.capability==="hands.connect"||J.capability==="display.stream.v1"||J.capability==="simulator.stream.v1"||aZ.has(J.capability)||J.capability==="pty.start",z,W=async(G,F,Y)=>{let N=z;z=void 0,await Promise.all([N,V(G,F,Y)])};try{if(U)z=V("started"),z.catch(()=>{return});else await V("started");let G={...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,(Y)=>V("pr-proof.started.v1",Y))}:{},claim:J,worker:Z.worker,claimOwner:J.owner,claimAuthority:J.authority,organizationId:$.orgId,deviceId:$.deviceId,apiOrigin:$.apiOrigin,root:K,payload:tZ(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:G,runCommand:Z.runCommand??KQ,spawnFullControl:Z.spawnFullControl??x3,emit:U?W:V,runHandsRelay:Z.runHandsRelay??((Y)=>V7(Y,G)),runPtySession:Z.runPtySession??w7});if(J.capability==="github.local.v1")d5.parse(F);if(!q3(F))throw new H("invalid_result","Operation result must be a JSON object.");if(Buffer.byteLength(JSON.stringify(F)??"null","utf8")>Y0)throw new H("result_too_large","Operation result exceeds 256 KB.");return await(U?W:V)("completed",{ok:!0}),{status:"succeeded",result:F,error_code:null}}catch(G){let F=Z.signal.reason instanceof H&&x5.has(Z.signal.reason.code)?Z.signal.reason.code:G instanceof H&&x5.has(G.code)?G.code:null;if(Z.signal.aborted||F)return{status:"cancelled",...G instanceof F7?{result:{process_terminal_observation:G.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)&&G instanceof Error&&"code"in G&&["EACCES","EPERM"].includes(String(G.code)))await V("permission.denied",{operation:J.capability==="fs.read"?"read":"write",provenance:"os_permission_unknown"});let Y=J.capability==="inference.custom.v1"?G instanceof H&&b6(G.code)?G.code:"custom_endpoint_unavailable":J.capability==="github.local.v1"?G instanceof O1&&g3(J.payload,"failed",G.code)?G.code:"local_github_unavailable":J.capability==="environment.install"?"environment_install_failed":G instanceof H&&rZ.test(G.code)?G.code:"capability_failed",N=J.capability==="hands.connect"&&G instanceof B7?t6(G.expiryDiagnostic):null;return await V("completed",{ok:!1,error_code:Y,...N?{expiry_diagnostic:N}:{}}),{status:"failed",error_code:Y}}}
539
+ export{rK as Xa,W0 as Ya,U$ as Za,X$ as _a,aK as $a,w$ as ab,z9 as bb,F9 as cb,R2 as db,q0 as eb,KJ as fb,aZ as gb,T7 as hb,q7 as ib,ZQ as jb,x3 as kb,KQ as lb,GQ as mb,XQ as nb,jQ as ob,b7 as pb,MQ as qb,LQ as rb,IQ as sb,OQ as tb,AQ as ub,DG as vb,jG as wb,MG as xb,LG as yb};