@kaeawc/auto-mobile 0.0.92 → 0.0.94

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 (257) hide show
  1. package/dist/build-info.json +12 -12
  2. package/dist/schemas/test-plan.schema.json +370 -52
  3. package/dist/src/ble-peripheral.py +153 -0
  4. package/dist/src/{chunk-r14wwk37.js → chunk-026y62r9.js} +12 -12
  5. package/dist/src/chunk-0jyfg947.js +4 -0
  6. package/dist/src/{chunk-950qcq1e.js → chunk-0zfpp1wh.js} +4 -4
  7. package/dist/src/chunk-13qxf7ym.js +7 -0
  8. package/dist/src/chunk-1scenrk7.js +4 -0
  9. package/dist/src/chunk-1vb5ph1k.js +4 -0
  10. package/dist/src/chunk-20g565q7.js +5 -0
  11. package/dist/src/chunk-21h6dhdm.js +5 -0
  12. package/dist/src/{chunk-2e6s75qv.js → chunk-25mfpthk.js} +8 -8
  13. package/dist/src/{chunk-9rkfyt6q.js → chunk-2b39zyxc.js} +3 -3
  14. package/dist/src/chunk-2gzd6wbd.js +4 -0
  15. package/dist/src/{chunk-eka89q3k.js → chunk-3dntffy9.js} +1 -1
  16. package/dist/src/chunk-3gfczcsn.js +4 -0
  17. package/dist/src/chunk-3h5jz1vb.js +9 -0
  18. package/dist/src/chunk-41zcy6b3.js +5 -0
  19. package/dist/src/chunk-47n9m2de.js +4 -0
  20. package/dist/src/chunk-4vxeq0vd.js +58 -0
  21. package/dist/src/chunk-59dx6qaf.js +4 -0
  22. package/dist/src/chunk-5sdf9y92.js +4 -0
  23. package/dist/src/chunk-5wk1t46v.js +5 -0
  24. package/dist/src/chunk-661c50hh.js +17 -0
  25. package/dist/src/chunk-68n6bjjd.js +21 -0
  26. package/dist/src/{chunk-zg67wjkh.js → chunk-69pmjdf2.js} +3 -3
  27. package/dist/src/chunk-6hrj3jt6.js +145 -0
  28. package/dist/src/{chunk-b4cxdzwy.js → chunk-6myr26wx.js} +8 -8
  29. package/dist/src/chunk-6n96k09n.js +4 -0
  30. package/dist/src/chunk-6vwrbkre.js +4 -0
  31. package/dist/src/chunk-6wk0yrab.js +4 -0
  32. package/dist/src/chunk-6yhm9een.js +4 -0
  33. package/dist/src/chunk-7k7gjg2t.js +7 -0
  34. package/dist/src/chunk-7n5fz68h.js +4 -0
  35. package/dist/src/chunk-8cvnpnbp.js +4 -0
  36. package/dist/src/chunk-8kzv7rk7.js +4 -0
  37. package/dist/src/chunk-8nj68t1v.js +167 -0
  38. package/dist/src/{chunk-r20pe1nv.js → chunk-96r3bpg7.js} +3 -3
  39. package/dist/src/chunk-97x887te.js +4 -0
  40. package/dist/src/{chunk-sz1a7p43.js → chunk-99a6tbvd.js} +1 -1
  41. package/dist/src/chunk-9p5d2994.js +5 -0
  42. package/dist/src/{chunk-w7zsh13a.js → chunk-9q265er0.js} +4 -4
  43. package/dist/src/chunk-9xgnrv5w.js +5 -0
  44. package/dist/src/chunk-9xgsmshb.js +5 -0
  45. package/dist/src/chunk-a02d1wgv.js +4 -0
  46. package/dist/src/{chunk-km0dy5vc.js → chunk-a9ps00a1.js} +10 -10
  47. package/dist/src/chunk-aewdveet.js +5 -0
  48. package/dist/src/chunk-b3tdtq7r.js +9 -0
  49. package/dist/src/chunk-bn7jx7a2.js +4 -0
  50. package/dist/src/chunk-bnyw27ja.js +4 -0
  51. package/dist/src/{chunk-s1zq65ny.js → chunk-bpwsg76p.js} +2 -2
  52. package/dist/src/chunk-bvranw3g.js +4 -0
  53. package/dist/src/chunk-c25a84zb.js +4 -0
  54. package/dist/src/chunk-c27yv1dx.js +5 -0
  55. package/dist/src/chunk-c3ewxm4x.js +5 -0
  56. package/dist/src/chunk-cb1ga9rd.js +7 -0
  57. package/dist/src/chunk-cn7fwy7k.js +4 -0
  58. package/dist/src/chunk-cnvy4a64.js +4 -0
  59. package/dist/src/chunk-cqhw4yr6.js +5 -0
  60. package/dist/src/{chunk-v90es00d.js → chunk-ctmfshjc.js} +2 -2
  61. package/dist/src/chunk-ctwmhz13.js +4 -0
  62. package/dist/src/{chunk-qv2918jt.js → chunk-d3jx9bz5.js} +2 -2
  63. package/dist/src/{chunk-wry6skrm.js → chunk-d6rb08ga.js} +1 -1
  64. package/dist/src/chunk-ddqhj4eg.js +5 -0
  65. package/dist/src/{chunk-d57432wq.js → chunk-ddrhs1c3.js} +2 -2
  66. package/dist/src/chunk-dnjnh9p6.js +4 -0
  67. package/dist/src/{chunk-ajsrz473.js → chunk-dw5rwgya.js} +3 -3
  68. package/dist/src/chunk-e0870khr.js +5 -0
  69. package/dist/src/chunk-ea3k10kj.js +4 -0
  70. package/dist/src/chunk-emv82m1w.js +7 -0
  71. package/dist/src/chunk-f3m6pdnx.js +4 -0
  72. package/dist/src/chunk-f84z32cb.js +4 -0
  73. package/dist/src/chunk-fpczgf0z.js +4 -0
  74. package/dist/src/chunk-g2js4c2v.js +971 -0
  75. package/dist/src/chunk-g3af2qbk.js +5 -0
  76. package/dist/src/chunk-gadtna7s.js +11 -0
  77. package/dist/src/{chunk-c9nk1r78.js → chunk-gcyx407v.js} +3 -3
  78. package/dist/src/{chunk-jdqvcq0a.js → chunk-gfpntwc1.js} +3 -3
  79. package/dist/src/chunk-gmnm5e3e.js +4 -0
  80. package/dist/src/chunk-gp6vb5gf.js +4 -0
  81. package/dist/src/chunk-gppgy7pa.js +4 -0
  82. package/dist/src/chunk-hegfz0ae.js +5 -0
  83. package/dist/src/chunk-hpzxdp1k.js +17 -0
  84. package/dist/src/{chunk-2v7tw1nj.js → chunk-j69g8b50.js} +3 -3
  85. package/dist/src/chunk-jvstjnqm.js +19 -0
  86. package/dist/src/chunk-jzqrv78s.js +4 -0
  87. package/dist/src/chunk-k2948b8d.js +4 -0
  88. package/dist/src/chunk-k4ftd40d.js +4 -0
  89. package/dist/src/chunk-kd9vfaxh.js +5 -0
  90. package/dist/src/{chunk-34zxqcmq.js → chunk-kdczmgwk.js} +3 -3
  91. package/dist/src/chunk-ke3wn14v.js +4 -0
  92. package/dist/src/chunk-kh5n7m6w.js +4 -0
  93. package/dist/src/{chunk-0dfnyfkh.js → chunk-khejfph4.js} +3 -3
  94. package/dist/src/chunk-kny2xemh.js +4 -0
  95. package/dist/src/chunk-knyzw9md.js +4 -0
  96. package/dist/src/chunk-mbzpt2hp.js +4 -0
  97. package/dist/src/chunk-mm8rcxad.js +4 -0
  98. package/dist/src/chunk-nc4516tx.js +4 -0
  99. package/dist/src/{chunk-stfzjr9y.js → chunk-ntfrqrqn.js} +5 -5
  100. package/dist/src/chunk-nz5h2j52.js +4 -0
  101. package/dist/src/chunk-p22s97qy.js +4 -0
  102. package/dist/src/chunk-p9kt1sgr.js +6 -0
  103. package/dist/src/{chunk-9y5bcy28.js → chunk-pf282r5g.js} +4 -4
  104. package/dist/src/chunk-pnd4mrxy.js +4 -0
  105. package/dist/src/chunk-pqqteyj6.js +4 -0
  106. package/dist/src/chunk-qj1tbnv2.js +8 -0
  107. package/dist/src/chunk-qnh9egwr.js +4 -0
  108. package/dist/src/chunk-qy3khhf8.js +8 -0
  109. package/dist/src/chunk-r0vp315h.js +11 -0
  110. package/dist/src/chunk-r4j43b9s.js +237 -0
  111. package/dist/src/{chunk-4pfftt07.js → chunk-r54cxxze.js} +3 -3
  112. package/dist/src/chunk-r6pvhj33.js +325 -0
  113. package/dist/src/chunk-rb7aa5gr.js +54 -0
  114. package/dist/src/chunk-rdj50kb4.js +4 -0
  115. package/dist/src/chunk-rnd4vcas.js +4 -0
  116. package/dist/src/chunk-s3y3zfcx.js +14 -0
  117. package/dist/src/chunk-s4g43k75.js +5 -0
  118. package/dist/src/chunk-sfqe223f.js +311 -0
  119. package/dist/src/chunk-sqdrxjw5.js +7 -0
  120. package/dist/src/{chunk-0w1spptt.js → chunk-t54k47em.js} +4 -4
  121. package/dist/src/chunk-tek4pnvv.js +26 -0
  122. package/dist/src/chunk-tn74y7af.js +4 -0
  123. package/dist/src/chunk-tvq0nzam.js +5 -0
  124. package/dist/src/chunk-tx4f0h9c.js +6 -0
  125. package/dist/src/chunk-vdqag3fj.js +5 -0
  126. package/dist/src/chunk-vz5zzs57.js +4 -0
  127. package/dist/src/chunk-w4s2vfpj.js +4 -0
  128. package/dist/src/chunk-w5yypt53.js +42 -0
  129. package/dist/src/{chunk-r0f1q783.js → chunk-w68v64vh.js} +3 -3
  130. package/dist/src/chunk-whwj0pdk.js +5 -0
  131. package/dist/src/chunk-wnmqt1dc.js +4 -0
  132. package/dist/src/{chunk-8en08r7q.js → chunk-wpe46vsa.js} +3 -3
  133. package/dist/src/chunk-wxdjeb4k.js +27 -0
  134. package/dist/src/chunk-xcqzwf9j.js +247 -0
  135. package/dist/src/chunk-xezekwwn.js +5 -0
  136. package/dist/src/chunk-xf19m15s.js +4 -0
  137. package/dist/src/chunk-xghbxha4.js +4 -0
  138. package/dist/src/{chunk-jhnbfj19.js → chunk-xn9m3xc2.js} +5 -5
  139. package/dist/src/{chunk-a4k9rt7z.js → chunk-yqfz4vts.js} +3 -3
  140. package/dist/src/chunk-z8tvs8nk.js +5 -0
  141. package/dist/src/chunk-zm2rehqb.js +5 -0
  142. package/dist/src/chunk-zs6dqm35.js +4 -0
  143. package/dist/src/daemon/processEntry.js +2 -2
  144. package/dist/src/index.js +4 -4
  145. package/dist/src/runtime/bunRuntimeGuard.js +2 -2
  146. package/dist/src/utils/workers/iosBundleExtractWorker.js +2 -2
  147. package/ios/CameraPosterInjection/Injection/CameraPosterInjection.m +466 -0
  148. package/package.json +4 -3
  149. package/schemas/test-plan.schema.json +370 -52
  150. package/dist/src/chunk-09442h7v.js +0 -4
  151. package/dist/src/chunk-0e4gm1kj.js +0 -5
  152. package/dist/src/chunk-0eb8576f.js +0 -4
  153. package/dist/src/chunk-0rjm4nx7.js +0 -5
  154. package/dist/src/chunk-1zmh2eak.js +0 -4
  155. package/dist/src/chunk-28k63ha3.js +0 -5
  156. package/dist/src/chunk-2d4wmp8b.js +0 -4
  157. package/dist/src/chunk-32jpxz2y.js +0 -323
  158. package/dist/src/chunk-3jmvqygr.js +0 -238
  159. package/dist/src/chunk-3swvfhqt.js +0 -5
  160. package/dist/src/chunk-44bt78m9.js +0 -5
  161. package/dist/src/chunk-488vt2bp.js +0 -4
  162. package/dist/src/chunk-4fgdhcwx.js +0 -5
  163. package/dist/src/chunk-4jp2se4w.js +0 -4
  164. package/dist/src/chunk-4vhr9e4t.js +0 -4
  165. package/dist/src/chunk-4xd6zs3y.js +0 -15
  166. package/dist/src/chunk-51567pg8.js +0 -4
  167. package/dist/src/chunk-5agqsfev.js +0 -4
  168. package/dist/src/chunk-5d706gmr.js +0 -4
  169. package/dist/src/chunk-5kd4rqk7.js +0 -5
  170. package/dist/src/chunk-61t538bm.js +0 -4
  171. package/dist/src/chunk-6d3mmqxt.js +0 -54
  172. package/dist/src/chunk-6hyt398x.js +0 -5
  173. package/dist/src/chunk-6mnr8kpm.js +0 -4
  174. package/dist/src/chunk-79q5xsdc.js +0 -42
  175. package/dist/src/chunk-7bdgand3.js +0 -4
  176. package/dist/src/chunk-84cp9dw5.js +0 -4
  177. package/dist/src/chunk-86f2h5ww.js +0 -5
  178. package/dist/src/chunk-8cghfzb2.js +0 -19
  179. package/dist/src/chunk-9tf2p9y9.js +0 -5
  180. package/dist/src/chunk-a2sc4jm0.js +0 -5
  181. package/dist/src/chunk-aa5ng3d1.js +0 -4
  182. package/dist/src/chunk-b3h0a6ca.js +0 -4
  183. package/dist/src/chunk-b6a737qt.js +0 -4
  184. package/dist/src/chunk-bn64x5z5.js +0 -5
  185. package/dist/src/chunk-bvh649za.js +0 -12
  186. package/dist/src/chunk-c9tyfg4j.js +0 -26
  187. package/dist/src/chunk-cfsdfqnm.js +0 -4
  188. package/dist/src/chunk-cxyf04jc.js +0 -7
  189. package/dist/src/chunk-da08tx5v.js +0 -4
  190. package/dist/src/chunk-f2tc08m2.js +0 -4
  191. package/dist/src/chunk-f8tnk179.js +0 -5
  192. package/dist/src/chunk-f9s1kkhx.js +0 -5
  193. package/dist/src/chunk-fbp8a4rx.js +0 -4
  194. package/dist/src/chunk-fd2z0sze.js +0 -4
  195. package/dist/src/chunk-fk927f4q.js +0 -54
  196. package/dist/src/chunk-fxmr3a0f.js +0 -4
  197. package/dist/src/chunk-gaqwhd44.js +0 -4
  198. package/dist/src/chunk-ggtd5x5a.js +0 -5
  199. package/dist/src/chunk-gndcfrm7.js +0 -4
  200. package/dist/src/chunk-h3n4adc6.js +0 -310
  201. package/dist/src/chunk-h5pjbb83.js +0 -4
  202. package/dist/src/chunk-hgnnh302.js +0 -4
  203. package/dist/src/chunk-hmke8nhx.js +0 -5
  204. package/dist/src/chunk-j2bx12hn.js +0 -4
  205. package/dist/src/chunk-j70y1a2g.js +0 -4
  206. package/dist/src/chunk-js1jpyxp.js +0 -6
  207. package/dist/src/chunk-kbjq0qvb.js +0 -4
  208. package/dist/src/chunk-kfwx57xd.js +0 -4
  209. package/dist/src/chunk-kzwctna2.js +0 -4
  210. package/dist/src/chunk-m9ehyehy.js +0 -4
  211. package/dist/src/chunk-mct91p1f.js +0 -4
  212. package/dist/src/chunk-mf9spd4g.js +0 -5
  213. package/dist/src/chunk-mgrcansb.js +0 -4
  214. package/dist/src/chunk-mqc1d0eb.js +0 -6
  215. package/dist/src/chunk-n1zmpk0z.js +0 -4
  216. package/dist/src/chunk-ncyjf63g.js +0 -4
  217. package/dist/src/chunk-nr64d21q.js +0 -973
  218. package/dist/src/chunk-nwm2pq5v.js +0 -168
  219. package/dist/src/chunk-pm06b05d.js +0 -9
  220. package/dist/src/chunk-q50s00ry.js +0 -4
  221. package/dist/src/chunk-qwye1958.js +0 -14
  222. package/dist/src/chunk-r8z9pfve.js +0 -5
  223. package/dist/src/chunk-rdpgkjf6.js +0 -4
  224. package/dist/src/chunk-rkr0dks9.js +0 -5
  225. package/dist/src/chunk-rn84t3sf.js +0 -11
  226. package/dist/src/chunk-s123kn7n.js +0 -4
  227. package/dist/src/chunk-s73qn3fx.js +0 -4
  228. package/dist/src/chunk-sjn0nj4p.js +0 -5
  229. package/dist/src/chunk-sns0c35v.js +0 -7
  230. package/dist/src/chunk-t4dr5c8v.js +0 -8
  231. package/dist/src/chunk-tc8k9c1j.js +0 -4
  232. package/dist/src/chunk-teznhase.js +0 -4
  233. package/dist/src/chunk-ty9xgmz4.js +0 -4
  234. package/dist/src/chunk-tyazf3sk.js +0 -145
  235. package/dist/src/chunk-v6npjrjm.js +0 -5
  236. package/dist/src/chunk-vbvtzkwz.js +0 -5
  237. package/dist/src/chunk-vefd8qee.js +0 -8
  238. package/dist/src/chunk-vs9r72ta.js +0 -17
  239. package/dist/src/chunk-w2mwa0jk.js +0 -4
  240. package/dist/src/chunk-w88k0bgr.js +0 -4
  241. package/dist/src/chunk-wzdt0enk.js +0 -4
  242. package/dist/src/chunk-xhhv854c.js +0 -4
  243. package/dist/src/chunk-y58270hd.js +0 -4
  244. package/dist/src/chunk-yk0hmbex.js +0 -4
  245. package/dist/src/chunk-ympy4fdz.js +0 -28
  246. package/dist/src/chunk-yw436axy.js +0 -4
  247. package/dist/src/chunk-z04jrpjy.js +0 -5
  248. package/dist/src/chunk-z2xznczw.js +0 -4
  249. package/dist/src/chunk-z4xnrgps.js +0 -4
  250. package/dist/src/chunk-z7csyszv.js +0 -4
  251. package/dist/src/chunk-z8t0v07j.js +0 -11
  252. package/dist/src/chunk-z916af47.js +0 -228
  253. package/dist/src/chunk-zcr8he8q.js +0 -5
  254. package/dist/src/chunk-zd9vmkzn.js +0 -9
  255. package/dist/src/chunk-zj939v0h.js +0 -5
  256. package/dist/src/chunk-zkdjwtc1.js +0 -4
  257. package/dist/src/chunk-zkv5kzt6.js +0 -4
@@ -0,0 +1,5 @@
1
+ // @bun
2
+ import{Ir,gt,ct,pe,ye,IV,kee,Gh}from"./chunk-6hrj3jt6.js";import{h,$e,nce}from"./chunk-5wk1t46v.js";import{i,e}from"./chunk-r0vp315h.js";import{Fr,N}from"./chunk-sfqe223f.js";import{RS,to}from"./chunk-xcqzwf9j.js";import{YS}from"./chunk-8nj68t1v.js";import{JQ,mv,m5,fv,f5,Ah,j0,P_,ZQ}from"./chunk-jvstjnqm.js";import{n,a,Me,S,s,kP,Ne,_}from"./chunk-w5yypt53.js";import{r,t}from"./chunk-2b39zyxc.js";var H="Invalid tools/call request: ",X="Invalid tools/call result: ",Z="AutoMobile drives Android and iOS devices. Start with listDevices, getAndroid or getApple, then bind your session. Call observe before acting and again after each action; element ids are only valid for the observation that returned them. Prefer tapOn/sendKeys on observed elements over raw coordinates. Large artifacts (screenshots, logs) are resources, not inline output. Read the automobile usage skill (skill://auto-mobile-usage/SKILL.md) for the full workflow before your first device call.";function ee(o=process.env){return $e(h.SERVER_INSTRUCTIONS,o)?Z:void 0}function RM(o,c,l={}){let{cacheHints:d,requestState:u,instructions:m=ee()}=l,p=new Gh(o,{capabilities:{...c,prompts:void 0},...d&&{cacheHints:d},...u&&{requestState:u},...m!==void 0&&{instructions:m}});if(c.prompts)p.server.registerCapabilities({prompts:c.prompts});return te(p.server),p}class q{result;constructor(o){this.result=o}}function te(o){let c=o._wrapHandler.bind(o);o._wrapHandler=(l,d)=>{if(l!=="tools/call")return c(l,(m,p)=>d(m,L(p)));let u=c(l,async(m,p)=>{let f=await d(m,L(p));if(Ah(f))throw new q(f);return f});return async(m,p)=>{try{return await u(m,p)}catch(f){if(f instanceof q)return f.result;throw re(f)}}}}function re(o){if(!(o instanceof ye)||o instanceof to||o.code!==pe.InvalidParams)return o;if(o.message.startsWith(H))return new ye(RS.InternalError,o.message.slice(H.length),o.data);if(o.message.startsWith(X))return new to(RS.InvalidParams,o.message,o.data);return o}function L(o){return{...o,mcpReq:{...o.mcpReq,signal:oe(o.mcpReq.signal)}}}function oe(o){let c=new AbortController,l=()=>{c.abort(ne(o.reason)?void 0:o.reason)};if(o.aborted)l();else o.addEventListener("abort",l,{once:!0});return c.signal}function ne(o){return o instanceof ct&&o.code===gt.ConnectionClosed}var D="x-auto-mobile-mcp-session-id";function KU(o){let c=o["x-auto-mobile-mcp-session-id"],l=Array.isArray(c)?c[0]:c;return typeof l==="string"&&l.length>0?l:void 0}var w=s({version:_(1),toolName:n(),argumentsHash:n(),deviceIds:S(n())}),ie={createSecret:()=>crypto.getRandomValues(new Uint8Array(32))},z=600000,ae=w.extend({expiresAt:a().finite()});function se(o){let c=KU({[D]:o.http?.req?.headers.get(D)??void 0});return JSON.stringify(["ambiguous-device",c??null])}function ce(o={}){let c=o.timer??i,l,d=()=>(l??=JQ({key:(o.secretProvider??ie).createSecret(),ttlSeconds:z/1000,bind:se}),l);return{mint:(u,m)=>d().mint({...u,expiresAt:c.now()+z},m),verify:async(u,m)=>{let p=ae.parse(await d().verify(u,m));if(c.now()>=p.expiresAt)throw Error("expired");return w.parse(p)}}}var GU=ce();import{createHash as Se}from"crypto";function $E(o=process.env){return nce(h.ELICITATION,o)!=="off"}class T{declined=new Set;static key(o){return[...new Set(o)].sort().join("\x00")}remembers(o){return this.declined.has(T.key(o))}remember(o){this.declined.add(T.key(o))}}function j(o){return typeof o==="object"&&o!==null&&!Array.isArray(o)}function zP(o){let c=j(o)?o.elicitation:void 0;if(!j(c))return"none";if(c.form!==void 0)return"form";return c.url!==void 0?"url":"bare"}function le(o){return`[elicitation] ${o.toolName} era=${o.era} declared=${o.declared} outcome=${o.outcome} candidates=${o.candidateCount}`+(o.latencyMs===void 0?"":` latencyMs=${o.latencyMs}`)}var B={record:(o)=>e.info(le(o))};function tJ(o){return{record(c){B.record(c),o.recordElicitationEvent(c)}}}var K=B;function rJ(o){K=o}var UE={record:(o)=>K.record(o)};var de=20000;function U(o){return typeof o==="object"&&o!==null&&!Array.isArray(o)}function PM(o){let c=U(o)?o.elicitation:void 0;if(!U(c))return!1;return c.form!==void 0||c.url===void 0}function V(o,c){return{declaresElicitation:()=>c.mcpReq.envelope===void 0&&PM(o.server.getClientCapabilities()),declaration:()=>c.mcpReq.envelope===void 0?zP(o.server.getClientCapabilities()):"none",elicit:(l,d)=>o.server.request({method:"elicitation/create",params:l},{signal:d})}}var ue=s({isError:_(!0),content:S(kP({type:n()})).min(1)}),me=s({code:_(YS),candidates:S(s({deviceId:n(),platform:n().default("unknown")}))}),fe=s({type:_("text"),text:n()});function ve(o){let c=ue.safeParse(o),l=c.success?fe.safeParse(c.data.content[0]):void 0;if(!l?.success||!l.data.text.includes(YS))return;try{let d=me.safeParse(JSON.parse(l.data.text));return d.success?d.data:void 0}catch(d){e.debug(`ambiguous device result is not JSON: ${r(d)}`);return}}function b(o){let c=new Map((ve(o)?.candidates??[]).map((l)=>[l.deviceId,l]));return c.size>1?[...c.values()]:void 0}function I(o,c){return{mode:"form",message:`${o} matched ${c.length} devices. Which device should it use?`,requestedSchema:{type:"object",properties:{deviceId:{type:"string",title:"Device",description:"The device this call should run on.",oneOf:c.map(({deviceId:l,platform:d})=>({const:l,title:`${l} (${d})`}))}},required:["deviceId"]}}}function ge(o,c){if(o.action!=="accept")return;let l=o.content?.deviceId;return typeof l==="string"&&c.some(({deviceId:d})=>d===l)?l:void 0}function Re(o,c){if(o.action!=="accept")return{outcome:o.action};let l=ge(o,c);return l===void 0?{outcome:"invalid"}:{outcome:"accept",deviceId:l}}async function Ce(o,c,l,d){let u=new AbortController,m=!1,p=()=>u.abort();d.callSignal.addEventListener("abort",p,{once:!0});let f=d.timer.setTimeout(()=>{m=!0,p()},d.timeoutMs);try{let v=await o.elicit(I(c,l),u.signal);return Re(v,l)}catch(v){if(u.signal.aborted)return e.debug(`device choice for ${c} not answered: ${r(v)}`),{outcome:m?"timeout":"cancel"};return e.warn(`device choice elicitation for ${c} failed: ${r(v)}`,v),{outcome:"error"}}finally{d.timer.clearTimeout(f),d.callSignal.removeEventListener("abort",p)}}function F(o,c,l={}){let d=l.timer??i,u=l.timeoutMs??de,m=l.recorder??UE,p=()=>c.declaration?.()??(c.declaresElicitation()?"form":"none"),f=l.enabled??(()=>$E()),v=(y,R,C)=>m.record({toolName:y.name,era:"legacy",declared:p(),outcome:C,candidateCount:R,atMs:d.now()}),g=(y)=>{if(!f())return"disabled";if(!c.declaresElicitation())return"not_offered";return l.declines?.remembers(y)?"remembered":void 0};return{...o,execute:async(y)=>{let R=await o.execute(y),C=y.args.deviceId===void 0?b(R):void 0;if(!C)return R;let E=C.map(({deviceId:Y})=>Y),A=g(E);if(A)return v(y,C.length,A),R;let Q=d.now(),x=await Ce(c,y.name,C,{timer:d,timeoutMs:u,callSignal:y.extra.signal}),O=d.now();if(m.record({toolName:y.name,era:"legacy",declared:p(),outcome:x.outcome,candidateCount:C.length,atMs:O,latencyMs:O-Q}),x.outcome==="decline"||x.outcome==="cancel")l.declines?.remember(E);return x.deviceId===void 0?R:o.execute({...y,args:{...y.args,deviceId:x.deviceId}})}}}async function YU(o,c,l,d){let u=await c(o),m=b(u);if(!m)return u;let p=d?.timer??i,f=p.now(),v=(R,C)=>{let E=p.now();d?.recorder.record({toolName:o.name,era:"modern",declared:d.declared,outcome:R,candidateCount:m.length,atMs:E,...C?{latencyMs:E-f}:{}})},g=await l({candidates:m,inputRequests:{deviceChoice:IV.elicit(I(o.name,m))}});if(!g)return v("not_offered",!1),u;if("pending"in g)return v("asked",!1),g.pending;let y=kee(g.responses,"deviceChoice",s({deviceId:n().refine((R)=>m.some(({deviceId:C})=>C===R)&&(g.offeredDeviceIds===void 0||g.offeredDeviceIds.includes(R)))}));return v(y?"accept":Ee(g.responses),!0),y?c({...o,args:{...o.args,deviceId:y.deviceId}}):u}function Ee(o){let c=o.deviceChoice,l=typeof c==="object"&&c!==null&&"action"in c?c.action:void 0;return l==="decline"||l==="cancel"?l:"invalid"}function W(o,c=UE,l=()=>$E()){return{...o,execute:async(d)=>{let u=!l();if(d.args.deviceId!==void 0||u||!PM(d.extra.envelope?.[Ir])){let f=await o.execute(d),v=d.args.deviceId===void 0&&b(f);if(v)xe(c,d,v.length,u?"disabled":"not_offered");return f}let m={...d.args};delete m.deviceId;let p=Se("sha256").update(Fr(m)).digest("hex");return YU(d,(f)=>o.execute(f),async({candidates:f,inputRequests:v})=>{if(d.extra.inputResponses!==void 0){let g=w.safeParse(d.extra.deviceChoiceState?.verified);if(!g.success||g.data.toolName!==d.name||g.data.argumentsHash!==p)return;return{responses:d.extra.inputResponses,offeredDeviceIds:g.data.deviceIds}}if(!d.extra.deviceChoiceState)return;return{pending:IV({requestState:await d.extra.deviceChoiceState.mint({version:1,toolName:d.name,argumentsHash:p,deviceIds:f.map(({deviceId:g})=>g)}),inputRequests:v})}},{recorder:c,declared:zP(d.extra.envelope?.[Ir])})}}}function xe(o,c,l,d){o.record({toolName:c.name,era:"modern",declared:zP(c.extra.envelope?.[Ir]),outcome:d,candidateCount:l,atMs:i.now()})}function Te(o,c){let l=o._meta?.progressToken;if(l===void 0)return;return async(d,u,m)=>{try{await o.sendNotification({method:"notifications/progress",params:{progressToken:l,progress:d,total:u,...m&&{message:m}}})}catch(p){e.warn(`${c}: ${p}`)}}}async function he(o,c,l){l.prepare?.(o);let d=o.params.name,u=o.params.arguments||{};if(!d)throw new t("Tool name is missing in the request");return l.execute({name:d,args:u,progressToken:c._meta?.progressToken,progress:Te(c,l.progressFailureMessage),extra:c})}function be(o,c){return{signal:o.mcpReq.signal,_meta:o.mcpReq._meta,...o.mcpReq.envelope!==void 0&&{envelope:o.mcpReq.envelope},...o.mcpReq.inputResponses!==void 0&&{inputResponses:o.mcpReq.inputResponses},...c&&{deviceChoiceState:{verified:o.mcpReq.requestState(),mint:(l)=>c.mint(l,o)}},sendNotification:(l)=>o.mcpReq.notify(l)}}function AM(o,c,l={}){let d=new T,u=l.era==="modern"?W(c):c,m=l.era==="modern"?l.deviceChoiceRequestState??GU:void 0;o.server.setRequestHandler("tools/call",async(p,f)=>await he(p,be(f,m),l.era!=="modern"&&l.ambiguousDeviceElicitation?F(c,V(o,f),{declines:d,...l.ambiguousDeviceElicitation}):u))}function iS(o,c=N.isToolResultsNoStructuredContentEnabled()){if(!o)return"no-schema";if(c)return"flag";return null}function mG(o){return o!==null&&typeof o==="object"&&"structuredContent"in o}function oS(o,c){if(c!==null&&mG(o))delete o.structuredContent;return o}var J=kP({taskId:n()}),we=kP({taskId:n(),inputResponses:Ne(n(),Me()).optional()});function fG(o){let c=o._oninitialize.bind(o);o.setRequestHandler("initialize",async(l,d)=>{let u=await c(l);if(!(f5(l.params.capabilities)||G(d)))return u;return{...u,capabilities:{...u.capabilities,extensions:{...u.capabilities.extensions,[mv]:{}}}}})}function G(o){return fv({envelope:o.mcpReq.envelope,meta:o.mcpReq._meta})}function M(o){if(!G(o))throw j0()}function P(o){if(!o.ownerKey)throw P_("not_found");return o.ownerKey}function nJ(o,c){let l=o.server;fG(l),l.setRequestHandler("tasks/get",{params:J},async(d,u)=>{M(u);let m=await c.taskManager.get(P(c),d.taskId);return ZQ(m)}),l.setRequestHandler("tasks/update",{params:we},async(d,u)=>{M(u);let m=u.mcpReq.inputResponses??d.inputResponses??{};return await c.taskManager.update(P(c),d.taskId,m),m5}),l.setRequestHandler("tasks/cancel",{params:J},async(d,u)=>(M(u),await c.taskManager.cancel(P(c),d.taskId),m5))}
3
+ export{RM,KU,GU,$E,zP,tJ,rJ,UE,PM,YU,AM,iS,mG,oS,fG,nJ};
4
+
5
+ //# debugId=282D5FB670E9D05F64756E2164756E21
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{Oo,sS,bt,Ff,Lf}from"./chunk-nwm2pq5v.js";import{i,si,e}from"./chunk-z8t0v07j.js";import{g}from"./chunk-mf9spd4g.js";import{cL,dw,yW,Kc,ru,Xu,kw,Zu,jh,Os,M,yi}from"./chunk-h3n4adc6.js";import{JN}from"./chunk-a2sc4jm0.js";import{WE,Fr}from"./chunk-qwye1958.js";import{L,Nt,_i,vi}from"./chunk-32jpxz2y.js";import"./chunk-ggtd5x5a.js";import"./chunk-79q5xsdc.js";import"./chunk-6d3mmqxt.js";import"./chunk-4fgdhcwx.js";import{Tb,cP,sM,s1,N,Qg,ey,ty,VE}from"./chunk-3jmvqygr.js";import"./chunk-hmke8nhx.js";import"./chunk-z04jrpjy.js";import{fe}from"./chunk-8cghfzb2.js";import"./chunk-tyazf3sk.js";import{t7}from"./chunk-44bt78m9.js";import"./chunk-jhnbfj19.js";import"./chunk-0e4gm1kj.js";import"./chunk-mqc1d0eb.js";import"./chunk-vefd8qee.js";import"./chunk-4xd6zs3y.js";import"./chunk-pm06b05d.js";import"./chunk-rn84t3sf.js";import"./chunk-vs9r72ta.js";import"./chunk-0rjm4nx7.js";import{hb,NO}from"./chunk-z916af47.js";import"./chunk-kbjq0qvb.js";import"./chunk-0w1spptt.js";import"./chunk-6hyt398x.js";import"./chunk-w7zsh13a.js";import"./chunk-ympy4fdz.js";import"./chunk-f9s1kkhx.js";import"./chunk-r20pe1nv.js";import"./chunk-cxyf04jc.js";import"./chunk-jdqvcq0a.js";import"./chunk-t4dr5c8v.js";import"./chunk-9y5bcy28.js";import"./chunk-zd9vmkzn.js";import"./chunk-c9nk1r78.js";import"./chunk-a4k9rt7z.js";import"./chunk-sjn0nj4p.js";import"./chunk-bn64x5z5.js";import"./chunk-sns0c35v.js";import"./chunk-zg67wjkh.js";import{r,t}from"./chunk-9rkfyt6q.js";function x(n,o,s={}){let a=cP(n);if(a&&/Unknown tool\b/i.test(o))return a;let l=o.replace(/[.]+$/,""),c=!s.gated&&/Unknown tool\b/i.test(o)?" Try: auto-mobile --daemon restart":"";return`Error calling daemon: ${l}.${c}`}function T(){hb(),NO({daemonMode:!0,includeDoctor:!0,includeToolSelection:!1})}function E(n){try{return{parsed:!0,value:JSON.parse(n)}}catch(o){return e.debug(`[cli] value is not JSON, treating as a raw token: ${n} (${o})`),{parsed:!1,value:n}}}function _(n,o){let s=()=>E(n).value;if(o?.nullable&&n==="null")return null;switch(o?.type){case"string":case"enum":return ie(n);case"number":case"bigint":return se(n);case"boolean":if(n==="true")return!0;if(n==="false")return!1;return s();default:return s()}}function ie(n){let{parsed:o,value:s}=E(n);return o&&typeof s==="string"?s:n}function se(n){let{parsed:o,value:s}=E(n);return o&&typeof s==="number"&&Number.isFinite(s)?s:n}var k=new Set(["optional","nullable","default","readonly","catch","branded","lazy"]);function A(n){let o=n?._def?.typeName??n?._def?.type??"unknown";return String(o).replace(/^Zod/,"").toLowerCase()}function U(n){let o=n?._def;return o?.innerType??o?.type??o?.schema??null}function ae(n){let o=n?._def?.options;if(!Array.isArray(o))return!1;let s=o.map((d)=>R(d).type),a=s.some((d)=>d==="number"||d==="bigint"),c=o.filter((d,u)=>s[u]==="string").every((d)=>{let u=d;for(let f=0;f<10&&u;f++){let m=A(u);if(m==="literal")return typeof(u._def?.value??u._def?.values?.[0])==="string";if(!k.has(m))return!1;u=U(u)}return!1});if(a&&c)return!1;return s.includes("string")&&s.every((d)=>["string","number","boolean","bigint"].includes(d))}function R(n){let o=n,s=!1;for(let a=0;a<10&&o;a++){let l=A(o);if(l==="nullable")s=!0;if(l==="literal")return{type:typeof(o._def?.value??o._def?.values?.[0]),nullable:s};if(l==="union"&&ae(o))return{type:"string",nullable:s};if(!k.has(l))return{type:l,nullable:s};o=U(o)}return{type:"unknown",nullable:s}}function C(n){let o=n?._def;if(!o)return[];if(o.shape)return[o.shape];let s=o.options??o.out?._def?.options;if(Array.isArray(s))return s.flatMap((a)=>C(a));return o.out?C(o.out):[]}function F(n){T();let o=N.getRegisteredTool(n);if(!o)return null;let s=C(o.schema);if(s.length===0)return null;let a=new Map;for(let l of s)for(let[c,d]of Object.entries(l)){let u=R(d),f=a.get(c)??{types:new Set,nullable:!1};f.types.add(u.type),f.nullable=f.nullable||u.nullable,a.set(c,f)}return Object.fromEntries([...a.entries()].filter(([,l])=>l.types.size===1).map(([l,c])=>[l,{type:[...c.types][0],nullable:c.nullable}]))}import le from"fs";var ce=65536,ue="CliToolResult";function B(n,o){let s=o.maxBytes??ce,a;try{a=JSON.stringify(n,null,2)}catch(c){return v(o.tool,0,`result is not JSON-serializable: ${r(c)}`)}if(a===void 0)return v(o.tool,0,"tool returned a value with no JSON representation");let l=Buffer.byteLength(a,"utf8");if(l<=s)return a;if(!o.artifactWriter)return v(o.tool,l,"no tool-output directory is available to spill the payload to");try{let c=o.artifactWriter.writeJsonArtifact({tool:o.tool,payload:ue,data:n,serialized:a});return JSON.stringify({truncated:!1,bytes:l,artifact:{...c.artifact,resourceUri:void 0},note:`Tool output was ${l} bytes, over the ${s}-byte CLI inline limit. The complete JSON result is in artifact.path.`},null,2)}catch(c){return e.debug(`[cli] failed to spill oversized tool output: ${r(c)}`),v(o.tool,l,r(c))}}function v(n,o,s){return JSON.stringify({truncated:!0,tool:n,bytes:o,reason:s,recovery:"Re-run with AUTOMOBILE_TOOL_OUTPUTS_DIR set to a writable directory, or narrow the request (for example observe with a scope) so the result fits inline."},null,2)}var H={write:(n)=>W(1,n)},j={write:(n)=>W(2,n)},de={writeSync:(n,o,s,a)=>le.writeSync(n,o,s,a),sleepSync:(n)=>{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,n)}},pe=1000;function me(n,o,s){let a=o+1;if(s.sleepSync(1),a>=pe)throw Error(`Zero-progress write to fd ${n} after ${a} attempts; refusing to spin`);return a}function W(n,o,s=de){let a=Buffer.from(o,"utf8"),l=0,c=0;while(l<a.length)try{let d=s.writeSync(n,a,l,a.length-l);if(d===0){c=me(n,c,s);continue}c=0,l+=d}catch(d){let u=d.code;if(u==="EAGAIN"){s.sleepSync(1);continue}if(u==="EPIPE"){e.debug(`[cli] output stream closed before the write completed (fd ${n})`);return}throw d}}function ge(n){if(!n||typeof n!=="object")return;let o=n,s=o.failure;if(s&&typeof s==="object")return s.code;let a=o.error;return o.code??(a&&typeof a==="object"?a.code:void 0)}function y(n){return n&&typeof n==="object"?n:void 0}function ye(n){return y(y(n)?.error)?.reason}function P(n){if(n<60000){let s=Math.round(n/1000*10)/10;return`${s} ${s===1?"second":"seconds"}`}let o=Math.round(n/60000*10)/10;return`${o} ${o===1?"minute":"minutes"}`}function he(n){let o=y(y(n)?.error)?.idleTimeoutMs;return typeof o==="number"&&Number.isFinite(o)&&o>0?o:void 0}var Se=`(reads do not count), so its session UUID cannot be used again. Acquire a new session with getAndroid, getApple or startDevice. To keep a session across longer gaps, set ${g.CLI_SESSION_IDLE_TIMEOUT_MS.name} (milliseconds, at most ${P(dw)}) in the environment of every --cli call.`;function be(n){let o=he(n);return`Hint: this --cli session went longer than ${o===void 0?`its idle timeout (${P(cL)} by default)`:`its idle timeout of ${P(o)} (${o} ms)`} without a control call ${Se}`}function we(n){let o=y(n)?.candidates;if(!Array.isArray(o))return[];return o.flatMap((s)=>{let a=y(s);if(typeof a?.deviceId!=="string")return[];return[typeof a.platform==="string"?`${a.deviceId} (${a.platform})`:a.deviceId]})}function Te(n){let o=we(n);return`Hint: more than one device matches this call. Re-run with --deviceId <id> to pick one, or with --session-uuid <uuid> to use a device your session holds.${o.length>0?` Candidates: ${o.join(", ")}.`:""}`}var ve=new Map([[Kc,"Hint: the device's previous session is still finishing its cleanup. Re-run the command after the retryAfterMs in the error has passed; nothing else needs to change."],[Xu,"Hint: the device is being shut down. Re-run the command after the retryAfterMs in the error has passed, once the shutdown has finished."],[Zu,"Hint: this session is being released because its device is being shut down, so its session UUID cannot be used again. Retrying with the same --session-uuid will not succeed; acquire the device again under a new session instead."],[jh,"Hint: the device's session is moving to another device. Re-run the command after the retryAfterMs in the error has passed, once the rebind has settled."],[kw,"Hint: the session no longer holds this device; it was rebound or released. Check who holds the device now with --daemon active-sessions before re-running the command."],[ru,"Hint: another AutoMobile daemon on this host is using the device. Re-run after it releases the device, or pass another deviceId."]]);function J(n,o){let s=ge(n);if(s===Oo&&ye(n)==="cli-idle-timeout")return be(n);if(s===sS)return Te(n);let a=typeof s==="string"?ve.get(s):void 0;if(a!==void 0)return a;if(s!==yW)return;if(Fr(o))return`Hint: another session holds the device, and ${o} cannot join it: acquisition tools mint their own session and the CLI ignores --session-uuid for them. If that session is yours, skip re-acquiring and pass --session-uuid <uuid> to your follow-up calls; to see who holds the device, run --daemon active-sessions (releasing a session that is not yours can break another agent's work); otherwise wait for the holder to release it.`;return`Hint: a device a session holds takes calls only from that session. Re-run with --session-uuid <uuid>, the sessionUuid that getAndroid, getApple or startDevice returned when the device was acquired, or wait for the holder to release it.${t7(o,"force")?" To stop it anyway, pass --force true.":""}`}import p from"fs";import q from"path";var Oe="tool-selection-profile",Ce=3000,Ee=50,_e=L.next(),Pe;function O(n){return q.join(si("cli",n),Oe)}function Ie(n){return`${O(n)}.lock`}async function I(n,o=process.env){let s=De(o,Pe??{});if(!await s.acquire())return!1;try{await n()}finally{s.release()}return!0}function De(n,o){let s=o.timer??i,a=Math.max(1,o.pollIntervalMs??Ee),l=o.timeoutMs??Ce,c=Ie(n),d=o.pid??process.pid,u=o.ownerToken??_e,f=s.now()+l;return{acquire:async()=>{try{for(;;){if(_i(c,{pid:d,isProcessRunning:o.isProcessRunning,ownerGeneration:o.ownerGeneration??Nt,reclaimOwnPid:!0,ownerToken:u}))return!0;if(s.now()>=f)return!1;await s.sleep(Math.min(a,f-s.now()))}}catch(m){return e.debug(`Unable to acquire CLI tool-selection profile lock: ${r(m)}`),!1}},release:()=>{vi(c,d,u)}}}function h(n=process.env){try{let o=p.readFileSync(O(n),"utf8").trim();if(o.length===0)return;if(!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(o)){e.debug("Ignoring persisted CLI tool-selection profile because the file content is not a valid UUID");return}return o}catch(o){e.debug(`Unable to load the persisted CLI tool-selection profile: ${r(o)}`);return}}function V(n=process.env){let o=O(n),s=q.dirname(o);try{if(p.accessSync(s,p.constants.W_OK),p.existsSync(o)){if(!p.statSync(o).isFile())throw Error("profile path is not a regular file");p.accessSync(o,p.constants.W_OK)}}catch(a){throw new t(`CLI tool-selection profile store is not writable: ${o}. Fix its permissions or set AUTOMOBILE_DATA_DIR/AUTO_MOBILE_DATA_DIR to a writable directory so the CLI can persist a stable tool-selection profile across invocations.`,{cause:a})}}function G(n,o=process.env){let s=n.trim();if(s.length===0)return;let a;try{let l=O(o);if(a=`${l}.${process.pid}.${L.next()}.tmp`,p.writeFileSync(a,s,{encoding:"utf8",mode:384}),process.platform!=="win32")p.chmodSync(a,384);if(p.renameSync(a,l),a=void 0,process.platform!=="win32")p.chmodSync(l,384)}catch(l){if(e.debug(`Unable to persist the CLI tool-selection profile: ${r(l)}`),a)try{p.unlinkSync(a)}catch(c){e.debug(`Unable to remove incomplete CLI tool-selection profile: ${r(c)}`)}}}function xe(n){let o=n/60000;return`${o} ${o===1?"minute":"minutes"}`}function Z(n){if(typeof n==="string"&&n.trim()==="")throw new t("--session-uuid requires a non-empty value")}function ke(n){let o=yi(n[0]);if(o.flag!=="--session-uuid")return{sessionUuid:void 0,toolNameIndex:0};let s=o.inlineValue!==void 0,a=s?o.inlineValue:n[1],l=s?1:2;if(n.length<=l)throw new t("--session-uuid requires a value and a tool name");return Z(a),{sessionUuid:a,toolNameIndex:l}}function Ae(n){return K(n,F)}function z(n,o){return n&&Object.hasOwn(n,o)?n[o]:void 0}function K(n,o){if(n.length===0)throw new t("No tool name provided. Usage: --cli [--session-uuid <uuid>] <tool-name> [--param value ...]");let{sessionUuid:s,toolNameIndex:a}=ke(n),l=n[a],c=new Map,d=o(l);for(let u=a+1;u<n.length;u++){let f=n[u];if(!f.startsWith("--"))throw new t(`Invalid parameter format: ${f}. Parameters must start with --`);let{flag:m,inlineValue:D}=yi(f),b=m.slice(2).replace(/-([a-z])/g,(Qe,re)=>re.toUpperCase());if(D!==void 0){c.set(b,_(D,z(d,b)));continue}let w=n[u+1],oe=w!==void 0&&/^---(?:\s|$)/.test(w);if(w===void 0||w.startsWith("--")&&!oe)c.set(b,!0);else u++,c.set(b,_(w,z(d,b)))}return Z(c.get("sessionUuid")),{toolName:l,sessionUuid:s,params:Object.fromEntries(c)}}var Le=(n)=>new VE(n);async function $e(n,o){if(o===bt)return;if(N.getTool(o)?.hidden)return;let s=h();if(!s){await Me(n,o);return}await Ue(n,o,s)}async function Ue(n,o,s){let a;try{n.setToolSelectionProfileUuid?.(s),a=await n.callTool(bt,{toolName:o,enabled:!0,sessionUuid:s})}catch(f){e.debug(`CLI pre-enable of ${o} did not apply: ${r(f)}`);return}let l=Ff(a);if(!(a?.isError===!0||l===void 0||l!==s))return;if(n.setToolSelectionProfileUuid?.(void 0),e.debug(`CLI tool-selection profile ${s} is stale; re-minting a profile`),await I(async()=>{let f=h();if(f&&f!==s){if(await X(n,o,f))return;n.setToolSelectionProfileUuid?.(void 0)}await Q(n,o)}))return;let u=h();e.debug(`CLI pre-enable of ${o} skipped after a contended profile-lock timeout; ${u?"a profile is now persisted for the next invocation":"the next invocation will retry"}, and the tool call will surface any gate error.`)}async function Me(n,o){if(!await I(async()=>{let a=h();if(a){if(await X(n,o,a))return;n.setToolSelectionProfileUuid?.(void 0)}await Q(n,o)})){let a=h();e.debug(`CLI pre-enable of ${o} skipped after a contended profile-lock timeout; ${a?"a profile is now persisted for the next invocation":"the next invocation will retry"}, and the tool call will surface any gate error.`)}}async function X(n,o,s){try{n.setToolSelectionProfileUuid?.(s);let a=await n.callTool(bt,{toolName:o,enabled:!0,sessionUuid:s}),l=Ff(a);return a?.isError!==!0&&l!==void 0&&l===s}catch(a){return e.debug(`CLI pre-enable of ${o} did not apply: ${r(a)}`),!0}}async function Q(n,o){V();try{let s=await n.callTool(bt,{toolName:o,enabled:!0}),a=Ff(s);G(a??"")}catch(s){e.debug(`CLI pre-enable of ${o} did not apply: ${r(s)}`)}}async function Ne(n,o,s){let a=Le({daemonOptions:s,oneShotCli:!0,lifecycleNamespaceEnv:process.env});try{await $e(a,n);let l=await a.callTool(n,o);if(l===null)throw new t(`Daemon returned null result. This may indicate a daemon connectivity issue. Try: bunx ${Os()} --daemon restart`);return l}catch(l){if(l instanceof Qg||l instanceof ey||l instanceof ty)throw new t(`Daemon preflight failed; no device operation started. ${l.message}`);if(l instanceof fe)throw new t(`Daemon became unavailable during tool execution: ${l.message}. Try: auto-mobile --daemon restart`);if(l instanceof t)throw l;let c=r(l);throw new t(x(n,c,{gated:JN(l)}))}finally{if(n!=="listDevices")await a.adoptCliSessionLiveness();await a.close()}}function Re(){return`Usage: auto-mobile --cli doctor [options]
2
+ import{Ho,YS,At,bh,Sh}from"./chunk-8nj68t1v.js";import{i,hi,e}from"./chunk-r0vp315h.js";import{h}from"./chunk-5wk1t46v.js";import{kB,oR,Zz,hd,Du,Mp,RR,Np,Lg,zs,N,ki}from"./chunk-sfqe223f.js";import"./chunk-z8tvs8nk.js";import{LI,Hr}from"./chunk-s3y3zfcx.js";import{B,kt,ti,Wn}from"./chunk-r6pvhj33.js";import"./chunk-aewdveet.js";import"./chunk-4vxeq0vd.js";import"./chunk-w5yypt53.js";import"./chunk-9xgnrv5w.js";import"./chunk-e0870khr.js";import{gS,iA,bN,AH,F,gA,Hy,qy,Vy,FI}from"./chunk-xcqzwf9j.js";import"./chunk-c3ewxm4x.js";import{ge}from"./chunk-jvstjnqm.js";import"./chunk-6hrj3jt6.js";import"./chunk-xn9m3xc2.js";import{pee}from"./chunk-xezekwwn.js";import"./chunk-cqhw4yr6.js";import"./chunk-tx4f0h9c.js";import"./chunk-qy3khhf8.js";import"./chunk-661c50hh.js";import"./chunk-b3tdtq7r.js";import"./chunk-gadtna7s.js";import"./chunk-tvq0nzam.js";import{sS,KM}from"./chunk-r4j43b9s.js";import"./chunk-8cvnpnbp.js";import"./chunk-t54k47em.js";import"./chunk-emv82m1w.js";import"./chunk-9q265er0.js";import"./chunk-hpzxdp1k.js";import"./chunk-wxdjeb4k.js";import"./chunk-g3af2qbk.js";import"./chunk-96r3bpg7.js";import"./chunk-13qxf7ym.js";import"./chunk-gfpntwc1.js";import"./chunk-qj1tbnv2.js";import"./chunk-pf282r5g.js";import"./chunk-3h5jz1vb.js";import"./chunk-gcyx407v.js";import"./chunk-yqfz4vts.js";import"./chunk-sqdrxjw5.js";import"./chunk-c27yv1dx.js";import"./chunk-vdqag3fj.js";import"./chunk-cb1ga9rd.js";import"./chunk-69pmjdf2.js";import{r,t}from"./chunk-2b39zyxc.js";function x(n,o,s={}){let a=iA(n);if(a&&/Unknown tool\b/i.test(o))return a;let l=o.replace(/[.]+$/,""),c=s.buildSkew?" Try: auto-mobile --daemon restart":"";return`Error calling daemon: ${l}.${c}`}function T(){sS(),KM({daemonMode:!0,includeDoctor:!0,includeToolSelection:!1})}function E(n){try{return{parsed:!0,value:JSON.parse(n)}}catch(o){return e.debug(`[cli] value is not JSON, treating as a raw token: ${n} (${o})`),{parsed:!1,value:n}}}function _(n,o){let s=()=>E(n).value;if(o?.nullable&&n==="null")return null;switch(o?.type){case"string":case"enum":return ie(n);case"number":case"bigint":return se(n);case"boolean":if(n==="true")return!0;if(n==="false")return!1;return s();default:return s()}}function ie(n){let{parsed:o,value:s}=E(n);return o&&typeof s==="string"?s:n}function se(n){let{parsed:o,value:s}=E(n);return o&&typeof s==="number"&&Number.isFinite(s)?s:n}var k=new Set(["optional","nullable","default","readonly","catch","branded","lazy"]);function A(n){let o=n?._def?.typeName??n?._def?.type??"unknown";return String(o).replace(/^Zod/,"").toLowerCase()}function L(n){let o=n?._def;return o?.innerType??o?.type??o?.schema??null}function ae(n){let o=n?._def?.options;if(!Array.isArray(o))return!1;let s=o.map((d)=>U(d).type),a=s.some((d)=>d==="number"||d==="bigint"),c=o.filter((d,u)=>s[u]==="string").every((d)=>{let u=d;for(let f=0;f<10&&u;f++){let m=A(u);if(m==="literal")return typeof(u._def?.value??u._def?.values?.[0])==="string";if(!k.has(m))return!1;u=L(u)}return!1});if(a&&c)return!1;return s.includes("string")&&s.every((d)=>["string","number","boolean","bigint"].includes(d))}function U(n){let o=n,s=!1;for(let a=0;a<10&&o;a++){let l=A(o);if(l==="nullable")s=!0;if(l==="literal")return{type:typeof(o._def?.value??o._def?.values?.[0]),nullable:s};if(l==="union"&&ae(o))return{type:"string",nullable:s};if(!k.has(l))return{type:l,nullable:s};o=L(o)}return{type:"unknown",nullable:s}}function C(n){let o=n?._def;if(!o)return[];if(o.shape)return[o.shape];let s=o.options??o.out?._def?.options;if(Array.isArray(s))return s.flatMap((a)=>C(a));return o.out?C(o.out):[]}function M(n){T();let o=F.getRegisteredTool(n);if(!o)return null;let s=C(o.schema);if(s.length===0)return null;let a=new Map;for(let l of s)for(let[c,d]of Object.entries(l)){let u=U(d),f=a.get(c)??{types:new Set,nullable:!1};f.types.add(u.type),f.nullable=f.nullable||u.nullable,a.set(c,f)}return Object.fromEntries([...a.entries()].filter(([,l])=>l.types.size===1).map(([l,c])=>[l,{type:[...c.types][0],nullable:c.nullable}]))}import le from"fs";var ce=65536,ue="CliToolResult";function R(n,o){let s=o.maxBytes??ce,a;try{a=JSON.stringify(n,null,2)}catch(c){return v(o.tool,0,`result is not JSON-serializable: ${r(c)}`)}if(a===void 0)return v(o.tool,0,"tool returned a value with no JSON representation");let l=Buffer.byteLength(a,"utf8");if(l<=s)return a;if(!o.artifactWriter)return v(o.tool,l,"no tool-output directory is available to spill the payload to");try{let c=o.artifactWriter.writeJsonArtifact({tool:o.tool,payload:ue,data:n,serialized:a});return JSON.stringify({truncated:!1,bytes:l,artifact:{...c.artifact,resourceUri:void 0},note:`Tool output was ${l} bytes, over the ${s}-byte CLI inline limit. The complete JSON result is in artifact.path.`},null,2)}catch(c){return e.debug(`[cli] failed to spill oversized tool output: ${r(c)}`),v(o.tool,l,r(c))}}function v(n,o,s){return JSON.stringify({truncated:!0,tool:n,bytes:o,reason:s,recovery:"Re-run with AUTOMOBILE_TOOL_OUTPUTS_DIR set to a writable directory, or narrow the request (for example observe with a scope) so the result fits inline."},null,2)}var H={write:(n)=>W(1,n)},j={write:(n)=>W(2,n)},de={writeSync:(n,o,s,a)=>le.writeSync(n,o,s,a),sleepSync:(n)=>{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,n)}},fe=1000;function pe(n,o,s){let a=o+1;if(s.sleepSync(1),a>=fe)throw Error(`Zero-progress write to fd ${n} after ${a} attempts; refusing to spin`);return a}function W(n,o,s=de){let a=Buffer.from(o,"utf8"),l=0,c=0;while(l<a.length)try{let d=s.writeSync(n,a,l,a.length-l);if(d===0){c=pe(n,c,s);continue}c=0,l+=d}catch(d){let u=d.code;if(u==="EAGAIN"){s.sleepSync(1);continue}if(u==="EPIPE"){e.debug(`[cli] output stream closed before the write completed (fd ${n})`);return}throw d}}function me(n){if(!n||typeof n!=="object")return;let o=n,s=o.failure;if(s&&typeof s==="object")return s.code;let a=o.error;return o.code??(a&&typeof a==="object"?a.code:void 0)}function g(n){return n&&typeof n==="object"?n:void 0}function ye(n){return g(g(n)?.error)?.reason}function P(n){if(n<60000){let s=Math.round(n/1000*10)/10;return`${s} ${s===1?"second":"seconds"}`}let o=Math.round(n/60000*10)/10;return`${o} ${o===1?"minute":"minutes"}`}function he(n){let o=g(g(n)?.error)?.idleTimeoutMs;return typeof o==="number"&&Number.isFinite(o)&&o>0?o:void 0}var Se=`(reads do not count), so its session UUID cannot be used again. Acquire a new session with getAndroid, getApple or startDevice. To keep a session across longer gaps, set ${h.CLI_SESSION_IDLE_TIMEOUT_MS.name} (milliseconds, at most ${P(oR)}) in the environment of every --cli call.`;function be(n){let o=he(n);return`Hint: this --cli session went longer than ${o===void 0?`its idle timeout (${P(kB)} by default)`:`its idle timeout of ${P(o)} (${o} ms)`} without a control call ${Se}`}function we(n){let o=g(n)?.candidates;if(!Array.isArray(o))return[];return o.flatMap((s)=>{let a=g(s);if(typeof a?.deviceId!=="string")return[];return[typeof a.platform==="string"?`${a.deviceId} (${a.platform})`:a.deviceId]})}function Te(n){let o=we(n);return`Hint: more than one device matches this call. Re-run with --deviceId <id> to pick one, or with --session-uuid <uuid> to use a device your session holds.${o.length>0?` Candidates: ${o.join(", ")}.`:""}`}var ve=new Map([[hd,"Hint: the device's previous session is still finishing its cleanup. Re-run the command after the retryAfterMs in the error has passed; nothing else needs to change."],[Mp,"Hint: the device is being shut down. Re-run the command after the retryAfterMs in the error has passed, once the shutdown has finished."],[Np,"Hint: this session is being released because its device is being shut down, so its session UUID cannot be used again. Retrying with the same --session-uuid will not succeed; acquire the device again under a new session instead."],[Lg,"Hint: the device's session is moving to another device. Re-run the command after the retryAfterMs in the error has passed, once the rebind has settled."],[RR,"Hint: the session no longer holds this device; it was rebound or released. Check who holds the device now with --daemon active-sessions before re-running the command."],[Du,"Hint: another AutoMobile daemon on this host is using the device. Re-run after it releases the device, or pass another deviceId."]]);function J(n,o){let s=me(n);if(s===Ho&&ye(n)==="cli-idle-timeout")return be(n);if(s===YS)return Te(n);let a=typeof s==="string"?ve.get(s):void 0;if(a!==void 0)return a;if(s!==Zz)return;if(Hr(o))return`Hint: another session holds the device, and ${o} cannot join it: acquisition tools mint their own session and the CLI ignores --session-uuid for them. If that session is yours, skip re-acquiring and pass --session-uuid <uuid> to your follow-up calls; to see who holds the device, run --daemon active-sessions (releasing a session that is not yours can break another agent's work); otherwise wait for the holder to release it.`;return`Hint: a device a session holds takes calls only from that session. Re-run with --session-uuid <uuid>, the sessionUuid that getAndroid, getApple or startDevice returned when the device was acquired, or wait for the holder to release it.${pee(o,"force")?" To stop it anyway, pass --force true.":""}`}import p from"fs";import q from"path";var Oe="tool-selection-profile",Ce=3000,Ee=50,_e=B.next(),Pe;function O(n){return q.join(hi("cli",n),Oe)}function Ie(n){return`${O(n)}.lock`}async function I(n,o=process.env){let s=De(o,Pe??{});if(!await s.acquire())return!1;try{await n()}finally{s.release()}return!0}function De(n,o){let s=o.timer??i,a=Math.max(1,o.pollIntervalMs??Ee),l=o.timeoutMs??Ce,c=Ie(n),d=o.pid??process.pid,u=o.ownerToken??_e,f=s.now()+l;return{acquire:async()=>{try{for(;;){if(ti(c,{pid:d,isProcessRunning:o.isProcessRunning,ownerGeneration:o.ownerGeneration??kt,reclaimOwnPid:!0,ownerToken:u}))return!0;if(s.now()>=f)return!1;await s.sleep(Math.min(a,f-s.now()))}}catch(m){return e.debug(`Unable to acquire CLI tool-selection profile lock: ${r(m)}`),!1}},release:()=>{Wn(c,d,u)}}}function y(n=process.env){try{let o=p.readFileSync(O(n),"utf8").trim();if(o.length===0)return;if(!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(o)){e.debug("Ignoring persisted CLI tool-selection profile because the file content is not a valid UUID");return}return o}catch(o){e.debug(`Unable to load the persisted CLI tool-selection profile: ${r(o)}`);return}}function V(n=process.env){let o=O(n),s=q.dirname(o);try{if(p.accessSync(s,p.constants.W_OK),p.existsSync(o)){if(!p.statSync(o).isFile())throw Error("profile path is not a regular file");p.accessSync(o,p.constants.W_OK)}}catch(a){throw new t(`CLI tool-selection profile store is not writable: ${o}. Fix its permissions or set AUTOMOBILE_DATA_DIR/AUTO_MOBILE_DATA_DIR to a writable directory so the CLI can persist a stable tool-selection profile across invocations.`,{cause:a})}}function G(n,o=process.env){let s=n.trim();if(s.length===0)return;let a;try{let l=O(o);if(a=`${l}.${process.pid}.${B.next()}.tmp`,p.writeFileSync(a,s,{encoding:"utf8",mode:384}),process.platform!=="win32")p.chmodSync(a,384);if(p.renameSync(a,l),a=void 0,process.platform!=="win32")p.chmodSync(l,384)}catch(l){if(e.debug(`Unable to persist the CLI tool-selection profile: ${r(l)}`),a)try{p.unlinkSync(a)}catch(c){e.debug(`Unable to remove incomplete CLI tool-selection profile: ${r(c)}`)}}}function xe(n){let o=n/60000;return`${o} ${o===1?"minute":"minutes"}`}function Z(n){if(typeof n==="string"&&n.trim()==="")throw new t("--session-uuid requires a non-empty value")}function ke(n){let o=ki(n[0]);if(o.flag!=="--session-uuid")return{sessionUuid:void 0,toolNameIndex:0};let s=o.inlineValue!==void 0,a=s?o.inlineValue:n[1],l=s?1:2;if(n.length<=l)throw new t("--session-uuid requires a value and a tool name");return Z(a),{sessionUuid:a,toolNameIndex:l}}function Ae(n){return K(n,M)}function z(n,o){return n&&Object.hasOwn(n,o)?n[o]:void 0}function K(n,o){if(n.length===0)throw new t("No tool name provided. Usage: --cli [--session-uuid <uuid>] <tool-name> [--param value ...]");let{sessionUuid:s,toolNameIndex:a}=ke(n),l=n[a],c=new Map,d=o(l);for(let u=a+1;u<n.length;u++){let f=n[u];if(!f.startsWith("--"))throw new t(`Invalid parameter format: ${f}. Parameters must start with --`);let{flag:m,inlineValue:D}=ki(f),b=m.slice(2).replace(/-([a-z])/g,(Qe,re)=>re.toUpperCase());if(D!==void 0){c.set(b,_(D,z(d,b)));continue}let w=n[u+1],oe=w!==void 0&&/^---(?:\s|$)/.test(w);if(w===void 0||w.startsWith("--")&&!oe)c.set(b,!0);else u++,c.set(b,_(w,z(d,b)))}return Z(c.get("sessionUuid")),{toolName:l,sessionUuid:s,params:Object.fromEntries(c)}}var Le=(n)=>new FI(n);async function $e(n,o){if(o===At)return;if(F.getTool(o)?.hidden)return;let s=y();if(!s){await Me(n,o);return}await Ue(n,o,s)}async function Ue(n,o,s){let a;try{n.setToolSelectionProfileUuid?.(s),a=await n.callTool(At,{toolName:o,enabled:!0,sessionUuid:s})}catch(f){e.debug(`CLI pre-enable of ${o} did not apply: ${r(f)}`);return}let l=bh(a);if(!(a?.isError===!0||l===void 0||l!==s))return;if(n.setToolSelectionProfileUuid?.(void 0),e.debug(`CLI tool-selection profile ${s} is stale; re-minting a profile`),await I(async()=>{let f=y();if(f&&f!==s){if(await X(n,o,f))return;n.setToolSelectionProfileUuid?.(void 0)}await Q(n,o)}))return;let u=y();e.debug(`CLI pre-enable of ${o} skipped after a contended profile-lock timeout; ${u?"a profile is now persisted for the next invocation":"the next invocation will retry"}, and the tool call will surface any gate error.`)}async function Me(n,o){if(!await I(async()=>{let a=y();if(a){if(await X(n,o,a))return;n.setToolSelectionProfileUuid?.(void 0)}await Q(n,o)})){let a=y();e.debug(`CLI pre-enable of ${o} skipped after a contended profile-lock timeout; ${a?"a profile is now persisted for the next invocation":"the next invocation will retry"}, and the tool call will surface any gate error.`)}}async function X(n,o,s){try{n.setToolSelectionProfileUuid?.(s);let a=await n.callTool(At,{toolName:o,enabled:!0,sessionUuid:s}),l=bh(a);return a?.isError!==!0&&l!==void 0&&l===s}catch(a){return e.debug(`CLI pre-enable of ${o} did not apply: ${r(a)}`),!0}}async function Q(n,o){V();try{let s=await n.callTool(At,{toolName:o,enabled:!0}),a=bh(s);G(a??"")}catch(s){e.debug(`CLI pre-enable of ${o} did not apply: ${r(s)}`)}}async function Ne(n,o,s){let a=Le({daemonOptions:s,oneShotCli:!0,lifecycleNamespaceEnv:process.env});try{await $e(a,n);let l=await a.callTool(n,o);if(l===null)throw new t(`Daemon returned null result. This may indicate a daemon connectivity issue. Try: bunx ${zs()} --daemon restart`);return l}catch(l){if(l instanceof Hy||l instanceof qy||l instanceof Vy)throw new t(`Daemon preflight failed; no device operation started. ${l.message}`);if(l instanceof ge)throw new t(`Daemon became unavailable during tool execution: ${l.message}. Try: auto-mobile --daemon restart`);if(l instanceof t)throw l;let c=r(l);throw new t(x(n,c,{buildSkew:l instanceof gA&&l.buildMismatch}))}finally{if(n!=="listDevices")await a.adoptCliSessionLiveness();await a.close()}}function Re(){return`Usage: auto-mobile --cli doctor [options]
3
3
 
4
4
  Status: status-only and read-only diagnostics.
5
5
 
@@ -9,9 +9,9 @@ Options:
9
9
  --json Machine-readable JSON output
10
10
  --help Print this help
11
11
 
12
- The universal --session-uuid option is accepted and ignored.`}function ee(n){if(Object.hasOwn(n,"repair")||Object.hasOwn(n,"timeoutMs"))return"doctor is status-only; --repair and --timeout-ms were removed. Use --daemon restart to recover the daemon; --daemon diagnose only gathers further diagnostics.";let o=["android","ios","json","help","sessionUuid"],s=Object.keys(n).filter((a)=>!o.includes(a)).map((a)=>`--${a.replace(/[A-Z]/g,(l)=>`-${l.toLowerCase()}`)}`);if(s.length>0)return`Unknown doctor flags: ${s.join(", ")}. Supported flags: --android, --ios, --json, --help (the universal --session-uuid option is accepted and ignored).`;return}function Fe(n){let o=ee(n);if(o!==void 0)throw new t(o)}function rn(n){let o;try{o=K(n,()=>null)}catch(s){return e.debug(`CLI bootstrap routing kept the normal path: ${r(s)}`),!1}if(o.toolName!=="doctor")return!1;return ee(o.params)!==void 0||Boolean(o.params.help)}async function Be(n,o={}){if(Fe(n),n.help){(o.writeOutput??console.log)(Re());return}let s=await import("./chunk-z2xznczw.js"),a=await(o.runDoctor??s.runDoctor)({android:n.android,ios:n.ios});if(n.json===!0)ne(a,"doctor");else(o.writeOutput??console.log)((o.formatConsoleOutput??s.formatConsoleOutput)(a,process.stdout.isTTY??!0));if(a.summary.failed>0)(o.exit??process.exit)(1);return}function te(n){let o=n;if(n&&typeof n==="object"&&"content"in n&&Array.isArray(n.content)){if(n.content.length>0&&n.content[0].type==="text")try{o=JSON.parse(n.content[0].text)}catch(s){e.debug(`CLI tool result is not JSON: ${r(s)}`),o=n}}return o}function He(n){return n?.isError===!0||te(n)?.success===!1}var je={stdout:H,stderr:j};function We(){try{return new sM({outputDirectory:M.getToolOutputsDir()??Lf(),retention:s1})}catch(n){e.debug(`[cli] no tool-output artifact writer available: ${r(n)}`);return}}function ne(n,o){je.stdout.write(B(n,{tool:o,artifactWriter:We()})+`
12
+ The universal --session-uuid option is accepted and ignored.`}function ee(n){if(Object.hasOwn(n,"repair")||Object.hasOwn(n,"timeoutMs"))return"doctor is status-only; --repair and --timeout-ms were removed. Use --daemon restart to recover the daemon; --daemon diagnose only gathers further diagnostics.";let o=["android","ios","json","help","sessionUuid"],s=Object.keys(n).filter((a)=>!o.includes(a)).map((a)=>`--${a.replace(/[A-Z]/g,(l)=>`-${l.toLowerCase()}`)}`);if(s.length>0)return`Unknown doctor flags: ${s.join(", ")}. Supported flags: --android, --ios, --json, --help (the universal --session-uuid option is accepted and ignored).`;return}function Fe(n){let o=ee(n);if(o!==void 0)throw new t(o)}function rn(n){let o;try{o=K(n,()=>null)}catch(s){return e.debug(`CLI bootstrap routing kept the normal path: ${r(s)}`),!1}if(o.toolName!=="doctor")return!1;return ee(o.params)!==void 0||Boolean(o.params.help)}async function Be(n,o={}){if(Fe(n),n.help){(o.writeOutput??console.log)(Re());return}let s=await import("./chunk-nc4516tx.js"),a=await(o.runDoctor??s.runDoctor)({android:n.android,ios:n.ios});if(n.json===!0)ne(a,"doctor");else(o.writeOutput??console.log)((o.formatConsoleOutput??s.formatConsoleOutput)(a,process.stdout.isTTY??!0));if(a.summary.failed>0)(o.exit??process.exit)(1);return}function te(n){let o=n;if(n&&typeof n==="object"&&"content"in n&&Array.isArray(n.content)){if(n.content.length>0&&n.content[0].type==="text")try{o=JSON.parse(n.content[0].text)}catch(s){e.debug(`CLI tool result is not JSON: ${r(s)}`),o=n}}return o}function He(n){return n?.isError===!0||te(n)?.success===!1}var je={stdout:H,stderr:j};function We(){try{return new bN({outputDirectory:N.getToolOutputsDir()??Sh(),retention:AH})}catch(n){e.debug(`[cli] no tool-output artifact writer available: ${r(n)}`);return}}function ne(n,o){je.stdout.write(R(n,{tool:o,artifactWriter:We()})+`
13
13
  `)}function Je(n){if(!n||typeof n!=="object")return n;let{message:o,nextAction:s}=n;if(typeof o!=="string")return n;return typeof s==="string"?`${o}
14
- Next: ${s}`:o}function qe(n,o){ne(n,o);let s=te(n);if(He(n)){if(s&&typeof s==="object"&&s.error)console.error(Je(s.error));else if(n?.isError===!0&&Array.isArray(n.content)&&n.content[0]?.type==="text")console.error(n.content[0].text);Ve(s,o);let a=J(s,o);if(a)console.error(a);process.exit(1)}}function Ve(n,o){if(o==="executePlan"&&n&&typeof n==="object"&&typeof n.executedSteps==="number"&&typeof n.totalSteps==="number"){if(console.error(`Executed ${n.executedSteps} of ${n.totalSteps} steps`),n.failedStep)console.error(`Failed at step ${n.failedStep.stepIndex+1}: ${n.failedStep.tool}`),console.error(`Step error: ${n.failedStep.error}`)}}async function sn(n,o,s=console){try{if(n.length===0){T(),Y(s);return}if(n[0]==="help"||n[0]==="--help"||n[0]==="-h"){if(T(),n.length>1)Ge(n[1],s);else Y(s);return}let{toolName:a,sessionUuid:l,params:c}=Ae(n);if(l)if(Fr(a))e.debug(`Ignoring session UUID for acquisition tool ${a}: it mints its own`);else c.sessionUuid=l,e.debug(`Using session UUID: ${l}`);if(a==="doctor")return await Be(c);e.debug(`Executing tool via daemon: ${a}`);let d=await Ne(a,c,o);qe(d,a)}catch(a){if(a instanceof t)e.error(`CLI Error: ${a.message}`),console.error(`Error: ${a.message}`);else e.error(`Unexpected CLI Error: ${a}`),console.error(`Unexpected error: ${a}`);process.exit(1)}}function Y(n){let o=N.getAllTools(),s=Os();n.log(`
14
+ Next: ${s}`:o}function qe(n,o){ne(n,o);let s=te(n);if(He(n)){if(s&&typeof s==="object"&&s.error)console.error(Je(s.error));else if(n?.isError===!0&&Array.isArray(n.content)&&n.content[0]?.type==="text")console.error(n.content[0].text);Ve(s,o);let a=J(s,o);if(a)console.error(a);process.exit(1)}}function Ve(n,o){if(o==="executePlan"&&n&&typeof n==="object"&&typeof n.executedSteps==="number"&&typeof n.totalSteps==="number"){if(console.error(`Executed ${n.executedSteps} of ${n.totalSteps} steps`),n.failedStep)console.error(`Failed at step ${n.failedStep.stepIndex+1}: ${n.failedStep.tool}`),console.error(`Step error: ${n.failedStep.error}`)}}async function sn(n,o,s=console){try{if(n.length===0){T(),Y(s);return}if(n[0]==="help"||n[0]==="--help"||n[0]==="-h"){if(T(),n.length>1)Ge(n[1],s);else Y(s);return}let{toolName:a,sessionUuid:l,params:c}=Ae(n);if(l)if(Hr(a))e.debug(`Ignoring session UUID for acquisition tool ${a}: it mints its own`);else c.sessionUuid=l,e.debug(`Using session UUID: ${l}`);if(a==="doctor")return await Be(c);e.debug(`Executing tool via daemon: ${a}`);let d=await Ne(a,c,o);qe(d,a)}catch(a){if(a instanceof t)e.error(`CLI Error: ${a.message}`),console.error(`Error: ${a.message}`);else e.error(`Unexpected CLI Error: ${a}`),console.error(`Unexpected error: ${a}`);process.exit(1)}}function Y(n){let o=F.getAllTools(),s=zs();n.log(`
15
15
  AutoMobile CLI - Android Device Automation
16
16
 
17
17
  Usage:
@@ -33,7 +33,7 @@ Options:
33
33
  help [tool-name] Show help for a specific tool
34
34
  --session-uuid <uuid> Associate tool execution with a session (optional).
35
35
  The CLI omits it for acquisition tools
36
- (${WE.join(", ")}), which mint
36
+ (${LI.join(", ")}), which mint
37
37
  their own session. For other tools, an undeclared
38
38
  sessionUuid is removed before strict validation.
39
39
 
@@ -50,7 +50,7 @@ Session-based Execution:
50
50
  When using --session-uuid, the tool will be executed on the device assigned to that session.
51
51
  This allows multiple tool calls to target the same device in parallel.
52
52
  A session acquired or used from the CLI is held on a wall-clock idle timeout
53
- (${xe(cL)} by default; override with
53
+ (${xe(kB)} by default; override with
54
54
  AUTOMOBILE_CLI_SESSION_IDLE_TIMEOUT_MS) rather than the
55
55
  heartbeat contract a long-running MCP connection keeps, so it survives the gap
56
56
  between one-shot invocations. Every control call refreshes it; reads do not.
@@ -69,10 +69,10 @@ Device ownership:
69
69
  Available Tools:`),n.log("================"),a.forEach((d,u)=>{n.log(`
70
70
  ${u}:`),d.forEach((f)=>{n.log(` ${f.name.padEnd(25)} - ${f.description}`)})}),n.log(`
71
71
  Total: ${o.length} tools available`),n.log(`
72
- Use 'bunx ${s} --cli help <tool-name>' for detailed information about a specific tool.`)}function Ge(n,o){let s=Os(),a=N.getTool(n);if(!a){o.error(`Unknown tool: ${n}`),o.log(`
72
+ Use 'bunx ${s} --cli help <tool-name>' for detailed information about a specific tool.`)}function Ge(n,o){let s=zs(),a=F.getTool(n);if(!a){o.error(`Unknown tool: ${n}`),o.log(`
73
73
  Use 'bunx ${s} --cli help' to see available tools.`);return}if(o.log(`
74
74
  Tool: ${a.name}`),o.log("=".repeat(a.name.length+6)),o.log(`Description: ${a.description}`),a.supportsProgress)o.log("Supports: Progress notifications");o.log(`
75
75
  Parameters:`),o.log(` Pass objects and arrays as JSON, e.g. --selector '{"text":"Submit"}'.`);try{let l=ze(a.schema);if(l)Object.entries(l).forEach(([c,d])=>{let u=Ye(d);if(o.log(` --${c} ${u.isOptional?"(optional)":"(required)"}`),o.log(` Type: ${u.typeName}`),u.description)o.log(` Description: ${u.description}`)});else o.log(" No parameters required")}catch(l){e.debug(`CLI parameter schema help unavailable: ${r(l)}`),o.log(" Could not parse parameter schema")}o.log(`
76
- Example usage:`),o.log(` bunx ${s} --cli ${n} [parameters...]`)}function ze(n){let o=n?._def;if(!o)return;if(o.shape)return o.shape;if(o.type==="pipe"&&o.out?._def?.shape)return o.out._def.shape;return}function Ye(n){let o=Ze(n),s=o?n?._def?.innerType??n:n,a=s?._def?.typeName??s?._def?.type??"unknown",l=String(a).replace(/^Zod/,"").toLowerCase(),c=["union","intersection","object","record","array","enum","literal","nullable"].includes(l)?S(Tb(s,{io:"input"})):l;return{isOptional:o,typeName:c,description:Ke(n,s)}}function Ze(n){return typeof n?.isOptional==="function"?n.isOptional():n?._def?.typeName==="ZodOptional"}function Ke(n,o){return n?.description??o?.description??o?._def?.description}function S(n){if(n.not&&Object.keys(n.not).length===0)return"never";if(n.allOf)return n.allOf.map((s)=>"("+S(s)+")").join(" & ");let o=n.anyOf??n.oneOf;if(o)return o.map((s)=>S(s)).join(" | ");if("const"in n)return JSON.stringify(n.const);if(n.enum)return n.enum.map((s)=>JSON.stringify(s)).join(" | ");if(n.type==="object")return Xe(n);if(n.type==="array")return"("+S(n.items??{})+")[] (JSON)";return n.type??"any"}function Xe(n){let o=Object.entries(n.properties??{}).map(([s,a])=>JSON.stringify(s)+(n.required?.includes(s)?"":"?")+": "+S(a));if(n.additionalProperties){let s=n.additionalProperties===!0?"any":S(n.additionalProperties);o.push("[key: string]: "+s)}return"JSON { "+o.join(", ")+" }"}export{rn as cliCommandSkipsServerBootstrap,sn as runCliCommand};
76
+ Example usage:`),o.log(` bunx ${s} --cli ${n} [parameters...]`)}function ze(n){let o=n?._def;if(!o)return;if(o.shape)return o.shape;if(o.type==="pipe"&&o.out?._def?.shape)return o.out._def.shape;return}function Ye(n){let o=Ze(n),s=o?n?._def?.innerType??n:n,a=s?._def?.typeName??s?._def?.type??"unknown",l=String(a).replace(/^Zod/,"").toLowerCase(),c=["union","intersection","object","record","array","enum","literal","nullable"].includes(l)?S(gS(s,{io:"input"})):l;return{isOptional:o,typeName:c,description:Ke(n,s)}}function Ze(n){return typeof n?.isOptional==="function"?n.isOptional():n?._def?.typeName==="ZodOptional"}function Ke(n,o){return n?.description??o?.description??o?._def?.description}function S(n){if(n.not&&Object.keys(n.not).length===0)return"never";if(n.allOf)return n.allOf.map((s)=>"("+S(s)+")").join(" & ");let o=n.anyOf??n.oneOf;if(o)return o.map((s)=>S(s)).join(" | ");if("const"in n)return JSON.stringify(n.const);if(n.enum)return n.enum.map((s)=>JSON.stringify(s)).join(" | ");if(n.type==="object")return Xe(n);if(n.type==="array")return"("+S(n.items??{})+")[] (JSON)";return n.type??"any"}function Xe(n){let o=Object.entries(n.properties??{}).map(([s,a])=>JSON.stringify(s)+(n.required?.includes(s)?"":"?")+": "+S(a));if(n.additionalProperties){let s=n.additionalProperties===!0?"any":S(n.additionalProperties);o.push("[key: string]: "+s)}return"JSON { "+o.join(", ")+" }"}export{rn as cliCommandSkipsServerBootstrap,sn as runCliCommand};
77
77
 
78
- //# debugId=55AD7D69952A9F9864756E2164756E21
78
+ //# debugId=080445F42826ACA664756E2164756E21
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{Pl}from"./chunk-2v7tw1nj.js";function wp(n){if(n instanceof Error){let e=[n.name,n.message].filter(Boolean).join(": "),o=n.stack?.split(`
3
- `).slice(0,3).join(" \u2190 "),i="cause"in n&&n.cause!==void 0?wp(n.cause):"";return[e||"Error",o,i?`cause=${i}`:""].filter(Boolean).join(" | ")}if(n===null||n===void 0)return String(n);if(typeof n==="object"){if(Object.keys(n).length===0)return`${Object.prototype.toString.call(n)} (no enumerable keys)`;return Pl(()=>JSON.stringify(n),()=>Object.prototype.toString.call(n))}return String(n)}function r(n){return Pl(()=>{if(n instanceof Error)return n.message;return String(n)},()=>Pl(()=>Object.prototype.toString.call(n),()=>"Unknown error"))}class t extends Error{constructor(n,e){super(n,e);let o=e?.containerFailure??(e?.cause instanceof t?e.cause.containerFailure:void 0);if(o)this.containerFailure=o}}function u(n,e){if(n instanceof t)return n;let o=r(n);return new t(`${e}: ${o}`,{cause:n})}function yt(n,e){return new t(`${e} is not supported on platform '${n}'. Supported platforms: android, ios.`)}export{wp,r,t,u,yt};
2
+ import{Kl}from"./chunk-j69g8b50.js";function im(n){if(n instanceof Error){let e=[n.name,n.message].filter(Boolean).join(": "),o=n.stack?.split(`
3
+ `).slice(0,3).join(" \u2190 "),i="cause"in n&&n.cause!==void 0?im(n.cause):"";return[e||"Error",o,i?`cause=${i}`:""].filter(Boolean).join(" | ")}if(n===null||n===void 0)return String(n);if(typeof n==="object"){if(Object.keys(n).length===0)return`${Object.prototype.toString.call(n)} (no enumerable keys)`;return Kl(()=>JSON.stringify(n),()=>Object.prototype.toString.call(n))}return String(n)}function r(n){return Kl(()=>{if(n instanceof Error)return n.message;return String(n)},()=>Kl(()=>Object.prototype.toString.call(n),()=>"Unknown error"))}class t extends Error{constructor(n,e){super(n,e);let o=e?.containerFailure??(e?.cause instanceof t?e.cause.containerFailure:void 0);if(o)this.containerFailure=o}}function u(n,e){if(n instanceof t)return n;let o=r(n);return new t(`${e}: ${o}`,{cause:n})}function Rt(n,e){return new t(`${e} is not supported on platform '${n}'. Supported platforms: android, ios.`)}export{im,r,t,u,Rt};
4
4
 
5
- //# debugId=E1CAB873E461C44964756E2164756E21
5
+ //# debugId=41BED146C6790E8864756E2164756E21
@@ -0,0 +1,4 @@
1
+ // @bun
2
+ import{vce,eG,tG,rG}from"./chunk-kd9vfaxh.js";import"./chunk-r54cxxze.js";import"./chunk-gadtna7s.js";import"./chunk-jvstjnqm.js";import"./chunk-xezekwwn.js";import"./chunk-z8tvs8nk.js";import"./chunk-xn9m3xc2.js";import"./chunk-6hrj3jt6.js";import"./chunk-c27yv1dx.js";import"./chunk-cqhw4yr6.js";import"./chunk-vdqag3fj.js";import"./chunk-e0870khr.js";import"./chunk-4vxeq0vd.js";import"./chunk-9xgnrv5w.js";import"./chunk-cb1ga9rd.js";import"./chunk-sfqe223f.js";import"./chunk-r6pvhj33.js";import"./chunk-w5yypt53.js";import"./chunk-aewdveet.js";import"./chunk-r0vp315h.js";import"./chunk-5wk1t46v.js";export{vce as createDirectModeAppearanceDeviceSource,eG as getAppearanceSocketPath,tG as startAppearanceSocketServer,rG as stopAppearanceSocketServer};
3
+
4
+ //# debugId=184C1E7D51901F5964756E2164756E21
@@ -1,4 +1,4 @@
1
1
  // @bun
2
- import{e}from"./chunk-z8t0v07j.js";import"./chunk-mf9spd4g.js";class i{inner;log;stoppedReason;answersOnlyReason;receivedRequestIds=new Set;pendingAnswerWrites=0;messageCallback;answerWait;constructor(s,n=(r)=>e.debug(r)){this.inner=s;this.log=n}stopSending(s){this.stoppedReason??=s,this.answerWait?.resolve()}answerReceivedThenStop(s){if(!this.answerWait)this.answerWait=Promise.withResolvers(),this.answersOnlyReason=s,this.stopIfAnswered();return this.answerWait.promise}stopIfAnswered(){if(this.stoppedReason!==void 0)this.answerWait?.resolve();else if(this.answersOnlyReason!==void 0&&this.receivedRequestIds.size===0&&this.pendingAnswerWrites===0)this.stopSending(this.answersOnlyReason)}async send(s,n){let r=!("method"in s)&&"id"in s?s.id:void 0,t=this.stoppedReason??(this.answersOnlyReason!==void 0&&(r===void 0||!this.receivedRequestIds.has(r))?this.answersOnlyReason:void 0);if(t!==void 0){this.log(`[OutputGatedTransport] Dropped ${"method"in s?s.method:"response"}: ${t}`);return}if(r===void 0)return this.inner.send(s,n);this.pendingAnswerWrites++;try{await this.inner.send(s,n)}finally{this.receivedRequestIds.delete(r),this.pendingAnswerWrites--,this.stopIfAnswered()}}start(){return this.inner.start()}close(){return this.inner.close()}get sessionId(){return this.inner.sessionId}setProtocolVersion(s){this.inner.setProtocolVersion?.(s)}get onmessage(){return this.messageCallback}set onmessage(s){this.messageCallback=s,this.inner.onmessage=(n,r)=>{if("method"in n&&"id"in n)this.receivedRequestIds.add(n.id);else if("method"in n&&n.method==="notifications/cancelled"){let t=n.params?.requestId;if(typeof t==="string"||typeof t==="number")this.receivedRequestIds.delete(t),this.stopIfAnswered()}s?.(n,r)}}get onclose(){return this.inner.onclose}set onclose(s){this.inner.onclose=s}get onerror(){return this.inner.onerror}set onerror(s){this.inner.onerror=s}}export{i as OutputGatedTransport};
2
+ import{e}from"./chunk-r0vp315h.js";import"./chunk-5wk1t46v.js";class i{inner;log;stoppedReason;answersOnlyReason;receivedRequestIds=new Set;pendingAnswerWrites=0;messageCallback;answerWait;constructor(s,n=(r)=>e.debug(r)){this.inner=s;this.log=n}stopSending(s){this.stoppedReason??=s,this.answerWait?.resolve()}answerReceivedThenStop(s){if(!this.answerWait)this.answerWait=Promise.withResolvers(),this.answersOnlyReason=s,this.stopIfAnswered();return this.answerWait.promise}stopIfAnswered(){if(this.stoppedReason!==void 0)this.answerWait?.resolve();else if(this.answersOnlyReason!==void 0&&this.receivedRequestIds.size===0&&this.pendingAnswerWrites===0)this.stopSending(this.answersOnlyReason)}async send(s,n){let r=!("method"in s)&&"id"in s?s.id:void 0,t=this.stoppedReason??(this.answersOnlyReason!==void 0&&(r===void 0||!this.receivedRequestIds.has(r))?this.answersOnlyReason:void 0);if(t!==void 0){this.log(`[OutputGatedTransport] Dropped ${"method"in s?s.method:"response"}: ${t}`);return}if(r===void 0)return this.inner.send(s,n);this.pendingAnswerWrites++;try{await this.inner.send(s,n)}finally{this.receivedRequestIds.delete(r),this.pendingAnswerWrites--,this.stopIfAnswered()}}start(){return this.inner.start()}close(){return this.inner.close()}get sessionId(){return this.inner.sessionId}setProtocolVersion(s){this.inner.setProtocolVersion?.(s)}get onmessage(){return this.messageCallback}set onmessage(s){this.messageCallback=s,this.inner.onmessage=(n,r)=>{if("method"in n&&"id"in n)this.receivedRequestIds.add(n.id);else if("method"in n&&n.method==="notifications/cancelled"){let t=n.params?.requestId;if(typeof t==="string"||typeof t==="number")this.receivedRequestIds.delete(t),this.stopIfAnswered()}s?.(n,r)}}get onclose(){return this.inner.onclose}set onclose(s){this.inner.onclose=s}get onerror(){return this.inner.onerror}set onerror(s){this.inner.onerror=s}}export{i as OutputGatedTransport};
3
3
 
4
4
  //# debugId=F996DBF661FB7D4564756E2164756E21
@@ -0,0 +1,4 @@
1
+ // @bun
2
+ import{Rce,cv,W4}from"./chunk-8nj68t1v.js";import"./chunk-aewdveet.js";import"./chunk-r0vp315h.js";import"./chunk-5wk1t46v.js";export{Rce as createTemplateMaintenance,cv as getDefaultSimulatorCreationService,W4 as stopTemplateBuilds};
3
+
4
+ //# debugId=C26C85BD92DE286664756E2164756E21
@@ -0,0 +1,9 @@
1
+ // @bun
2
+ import{i,tS,OU,Ld,Se,LK,Jae,$K,zt,qf,l,st,H8,e}from"./chunk-r0vp315h.js";import{h}from"./chunk-5wk1t46v.js";import{G4,Yc,EQ}from"./chunk-8nj68t1v.js";import{MK,nM}from"./chunk-aewdveet.js";import{w,yB,Fr,Gre,ld,RB,Bt,yz,Sr,vz,Jre,on,bz,oo,ik,bD,Xre,Zre,vl,Pp,Rz,ene,di,bl,Sl,lne,une,eb,_o,cR,pne,kn,sb,zs,ER,aj,ff,JB,CY,$D,l$}from"./chunk-sfqe223f.js";import{Vo,ge,A_,fV,Da}from"./chunk-jvstjnqm.js";import{B,_d,Dr,Za,Ta,kt,fy,Es,AP,ti,Wn,Kb,WO}from"./chunk-r6pvhj33.js";import{y,T,te,g,Dt,ne,A}from"./chunk-w5yypt53.js";import{aD}from"./chunk-4vxeq0vd.js";import{P4}from"./chunk-hpzxdp1k.js";import{Hc}from"./chunk-khejfph4.js";import{r,t}from"./chunk-2b39zyxc.js";import{Pt}from"./chunk-j69g8b50.js";var rq="ide/republishIdentity",nq="ide/prepareRestart",iq="ide/prepareMaintenance",oq="ide/completeMaintenance",sq="ide/restartAdmitted",aq="ide/restartAcceptanceSession",cq="ide/commitAcceptanceRestart",dq="ide/releaseAcceptanceRestart",ce=1000;class Or extends ge{refusalReason;code="daemon_restart_deferred";retryable=!0;retryAfterMs=ce;constructor(o,n){super(`AutoMobile daemon restart deferred (${o}). Retry after ${ce}ms; use an explicit daemon restart only after confirming that no device operation is active.`);this.refusalReason=n;this.name="DaemonRestartDeferredError"}}function qI(o){return{error:{code:o.code,message:o.message,retryable:o.retryable,retryAfterMs:o.retryAfterMs}}}import{createServer as or}from"net";import{rm as Ne}from"fs/promises";import{resolve as de,sep as _}from"path";import{tmpdir as xe}from"os";function me(o){let a=de(o).split(_),s=a.lastIndexOf("node_modules");if(s<=0)return null;if(a.slice(s+1,s+3).join("/")!=="@kaeawc/auto-mobile")return null;let d=a.slice(0,s).join(_)||_;if(d===_)return null;let m=de(xe());if(!Hc(m,d,{allowEqual:!1}))return null;return d}var le={async removeExtractionForEntryScript(o){let n=me(o);if(!n)return!1;return await Ne(n,{recursive:!0,force:!0}),!0}};import{readFileSync as Ge,rmSync as He,writeFileSync as $e}from"fs";var IA={readFileSync:Ge,writeFileSync:$e,rmSync:He},pe=1800000,Ue=g({reason:A(["orphan-watchdog","database-health","startup-failure","unexpected-exit"]),exitedAtMs:T().finite(),buildId:y(),options:A_});function H(o){return`${o}.exit-record.json`}function AZ(o,n,a=IA){try{a.writeFileSync(H(o),JSON.stringify(n))}catch(s){e.warn(`Failed to record daemon self-exit: ${r(s)}`,s)}}function O(o,n=IA){try{n.rmSync(H(o),{force:!0})}catch(a){e.warn(`Failed to remove daemon exit record: ${r(a)}`,a)}}function he(o,n=IA){let a=H(o),s;try{s=n.readFileSync(a,"utf8")}catch(c){e.debug(`No daemon exit record at ${a}: ${r(c)}`);return}O(o,n);try{let c=JSON.parse(s),d=Ue.safeParse(c);if(d.success)return d.data;e.warn(`Ignoring malformed daemon exit record ${a}: ${d.error.message}`)}catch(c){e.warn(`Ignoring malformed daemon exit record ${a}: ${r(c)}`,c)}return}function U(o,n){let a={...o,...n};if(n.enabledTools!==void 0&&n.disabledTools===void 0&&o.disabledTools!==void 0)a.disabledTools=o.disabledTools.filter((s)=>!n.enabledTools?.includes(s));if(n.disabledTools!==void 0&&n.enabledTools===void 0&&o.enabledTools!==void 0)a.enabledTools=o.enabledTools.filter((s)=>!n.disabledTools?.includes(s));return a}function fe(o,n,a,{ttl:s,buildId:c}){let d=Object.fromEntries(Object.entries(o).filter(([,p])=>p!==void 0));if(!n)return{options:d,outcome:"none",inheritedPort:!1};if(a-n.exitedAtMs>s)return{options:d,outcome:"stale",inheritedPort:!1};if(n.buildId!==c)return{options:d,outcome:"build-mismatch",inheritedPort:!1};let m=Object.fromEntries(Object.entries(d).filter(([,p])=>p!==!1)),u={...n.options};if(d.port!==void 0)delete u.port,delete u.strictPort;return{options:U(u,m),outcome:"inherited",inheritedPort:d.port===void 0&&u.port!==void 0}}class l4{deps;cleanStop=!1;recorded=!1;constructor(o){this.deps=o}markCleanStop(){this.cleanStop=!0}record(o){if(this.cleanStop||this.recorded)return;try{if(!this.deps.canRecord())return;this.recorded=!0,this.deps.write({reason:o,exitedAtMs:this.deps.now(),buildId:this.deps.buildId(),options:this.deps.options()})}catch(n){e.warn(`Failed to record daemon self-exit: ${r(n)}`,n)}}}import{existsSync as nr,openSync as ar,closeSync as ir}from"fs";import{existsSync as Be,readFileSync as We}from"fs";class W{host;constructor(o){this.host=o}cleanupSocketPaths(o){if(this.host.pidFilePath===Sr)return;return o?[o]:[]}findAllDaemonProcesses(o){try{return this.normalizeDaemonProcessRecords(this.host.processFinder.findDaemonProcesses(o))}catch(n){throw new t(`Failed to inspect daemon process table: ${r(n)}`)}}findOtherDaemonProcesses(o){return this.host.findLiveDaemonProcessRecords().filter((n)=>this.host.hasNamespaceRecordOrMarker(n)).map((n)=>n.pid).filter((n)=>n!==o)}findLiveDaemonProcesses(o){return this.host.findAllDaemonProcesses(o).filter((n)=>this.host.isProcessRunning(n))}findLiveDaemonProcessRecords(o){try{let n=this.host.processFinder.findDaemonProcesses(o),a=new Set(this.normalizeDaemonProcessRecords(n));return n.filter((s)=>a.has(s.pid)&&this.host.isProcessRunning(s.pid)).map((s)=>({...s,socketPath:JB(s.command)}))}catch(n){throw new t(`Failed to inspect daemon process table: ${r(n)}`)}}hasNamespaceRecordOrMarker(o){if(o.socketPath!==void 0)return o.socketPath===this.host.socketPath;if(o.command.includes(ff))return!1;let n=this.host.recordedStatus();return n.running&&n.pid===o.pid&&this.host.matchesRecordedDaemonGeneration(n,o)}async probeNamespaceOwner(){try{let o=await this.host.identityRecoveryIO.probe();return o.running&&o.pid!==void 0&&this.host.isProcessRunning(o.pid)&&(o.reportedSocketPath===void 0||o.reportedSocketPath===this.host.socketPath)&&(o.reportedPidFilePath===void 0||o.reportedPidFilePath===this.host.pidFilePath)?o:void 0}catch(o){if(/ECONNREFUSED|ENOENT|Daemon socket not found|Failed to connect to daemon|timed out/i.test(r(o)))e.debug("No namespace socket owner available for daemon discovery",o);else e.warn("Failed to probe namespace socket ownership",o);return}}async findNamespaceDaemonProcessRecords(o){let n=this.host.findLiveDaemonProcessRecords(o),a=!this.host.recordedStatus().running||n.some((s)=>!this.host.hasNamespaceRecordOrMarker(s)&&!s.command.includes(ff))?await this.host.probeNamespaceOwner():void 0;if(a?.pid!==void 0&&!n.some((s)=>s.pid===a.pid))n.push({pid:a.pid,ppid:0,command:"",startedAt:a.processStartedAt??a.startedAt,processGenerationToken:Dr(a)});return n.filter((s)=>{let c=this.host.hasNamespaceRecordOrMarker(s)||!s.command.includes(ff)&&a?.pid===s.pid;if(!c)e.debug(`Ignoring daemon PID ${s.pid}: no evidence for this socket namespace`);return c})}async findLiveDaemonProcessesForStart(o,n){if(this.host.remainingTime(n)<=0)throw new t("Daemon startup deadline elapsed before process-table inspection could complete; refusing to launch a daemon after the client deadline.");let s=zt(Zre),c=await this.host.retryExecutor.execute(async()=>{let p=this.host.remainingTime(n);if(p<=0)throw Error("Process-table inspection ETIMEDOUT before daemon startup deadline");return(await this.host.findNamespaceDaemonProcessRecords(Math.min(bD,p))).map((D)=>D.pid)},{maxAttempts:Xre,expectedFailure:{reason:"Startup handles scan timeouts with namespace ownership probes and a degradation warning",matches:(p)=>p.message.includes("ETIMEDOUT")},delays:(p)=>Math.min(s.delayForAttempt(p),this.host.remainingTime(n)),shouldRetry:(p)=>p.message.includes("ETIMEDOUT")&&this.host.remainingTime(n)>0});if(this.host.remainingTime(n)<=0)throw new t("Daemon startup deadline elapsed during process-table inspection; refusing to launch a daemon after the client deadline.");if(c.success)return c.value??[];let d=c.error??Error("Process-table inspection failed without an error");if(!d.message.includes("ETIMEDOUT"))throw d;let m=await this.host.probeNamespaceOwner();if(m?.pid!==void 0)return[m.pid];if(await this.findOccupiedDaemonStartPort(this.degradedStartProbeTargets(o),this.host.remainingTime(n))===void 0)o.strictPort=!0;return e.warn(`[DaemonManager] process-table inspection timed out during daemon start; proceeding with namespace ownership checks: ${r(d)}`,d),[]}degradedStartProbeTargets(o){let n=[...new Set([o.host??j,...je])];return this.degradedStartProbePorts(o).flatMap((a)=>n.map((s)=>({host:s,port:a})))}degradedStartProbePorts(o){let n=o.port??ld,a=[n];if(ld!==n)a.push(ld);let s=this.readPersistedDaemonOwnerPortForStart();if(s!==void 0&&!a.includes(s))a.push(s);return a}readPersistedDaemonOwnerPortForStart(){if(!Be(this.host.pidFilePath)){e.debug(`[DaemonManager] no persisted daemon owner record was available while widening the degraded process-table scan probe: ${this.host.pidFilePath}`);return}try{let o=JSON.parse(We(this.host.pidFilePath,"utf8"));if(typeof o.port==="number")return o.port;e.debug(`[DaemonManager] persisted daemon owner record has no usable port while widening the degraded process-table scan probe: ${this.host.pidFilePath}`)}catch(o){e.debug(`[DaemonManager] failed to read persisted daemon owner record while widening the degraded process-table scan probe: ${r(o)}`)}return}async findOccupiedDaemonStartPort(o,n){let a=await Promise.all(o.map((s)=>this.host.portAvailabilityChecker.isPortFree(s.port,s.host,n)));return o.find((s,c)=>!a[c])}normalizeDaemonProcessRecords(o){let n=new Set,a=new Set(o.map((d)=>d.ppid));for(let d of o)if(CY(d.command)&&a.has(d.pid))n.add(d.pid);let s=[],c=new Set;for(let d of o){if(d.pid===process.pid||n.has(d.pid)||c.has(d.pid))continue;s.push(d.pid),c.add(d.pid)}return s}}var j="127.0.0.1",je=["127.0.0.1","::1"];import{readFile as mt}from"fs/promises";import{constants as Pe,openSync as lt,closeSync as ut,fstatSync as pt,readFileSync as ve,writeSync as ht}from"fs";import{basename as ft,isAbsolute as yt}from"path";import{open as ze}from"fs/promises";import{join as Ye}from"path";import{devNull as Xe}from"os";var Ve=["enabledTools","disabledTools","toolResultsNoStructuredContent","actionsCompactMetadata"],Ke=["toolResultsNoStructuredContent","actionsCompactMetadata"],Je=[h.ENABLED_TOOLS.name,h.DISABLED_TOOLS.name,"AUTOMOBILE_TOOL_RESULTS_NO_STRUCTURED_CONTENT","AUTOMOBILE_ACTIONS_COMPACT_METADATA"];function os(o){let n={...o??{}};for(let a of Ke)delete n[a];return n}function u4(o){let n={...o??{}};for(let a of Ve)delete n[a];return n}var qe="BUN_FEATURE_FLAG_NO_ORPHANS";function De(o){let n={...o};for(let a of[...Je,qe])delete n[a];return n}class V{host;constructor(o){this.host=o}async launchWithExtractionRetry(o,n,a,s){let{options:c,childEnv:d,logSink:m,capturesLaunchOutput:u,logFd:p,logPath:D}=o,{command:b,args:S,packageRunner:v}=n,ie=!1;while(!0){let se=this.host.remainingTime(a);if(se<=0)throw new t("Daemon startup deadline elapsed before launch; refusing to start a daemon after the client deadline.");try{this.host.throwIfRecoveryCancelled(s);let R,I=v?this.host.seams.nextLaunchNonce():void 0;await this.host.launcher.launchAndWait({command:b,args:S,spawnOptions:{detached:!0,cwd:this.host.seams.launchWorkingDirectory(),stdio:["ignore",u?p:"ignore",m==="stderr"||m==="both"?"pipe":p],env:{...d,[Gre]:I}},onSpawn:(P)=>{if(R=P.pid,m==="stderr"||m==="both")be(P)},timeoutMs:se,waitForReady:(P,L)=>this.host.waitForReady(P,{signal:L,launchedProcess:{pid:R,launchNonce:I}}),isReadyForLaunchedProcess:(P,L,Me)=>this.host.isLaunchedProcessReady(P,L,Me,I),formatFailure:(P)=>this.createDaemonStartupFailure(P,D),formatExitFailure:(P,L)=>this.host.createDaemonExitFailure(P,L,D)});break}catch(R){if(!this.isIncompleteExtractionStartupError(R)||ie)throw R;if(ie=!0,!await this.removeIncompleteExtraction(S[0],R,s))throw R;({command:b,args:S,packageRunner:v}=this.host.withDaemonOptions(this.host.fallbackLauncher.resolveCommand(),c)),f(`Detected incomplete daemon package extraction (${Kb}); removed it and retrying once...`)}}}async removeIncompleteExtraction(o,n,a){try{let s=o?await this.host.extractionCleaner.removeExtractionForEntryScript(o):!1;return this.host.throwIfRecoveryCancelled(a),s}catch(s){throw new t(`${this.host.describeError(n)}
3
+ Failed to remove incomplete extraction before retry: ${this.host.describeError(s)}`)}}daemonLaunchEnvironment(o){let n=De(process.env);if(this.host.recoveryOwner?.dbPath)n.AUTOMOBILE_DB_PATH=this.host.recoveryOwner.dbPath;if(n[tS]=Ld(),this.host.pidFilePath!==Sr)n[h.DAEMON_PID_FILE_PATH.name]=this.host.pidFilePath;if(this.host.lockFilePath!==vz)n[h.DAEMON_LOCK_FILE_PATH.name]=this.host.lockFilePath;if(this.host.socketPath!==Bt)n[h.DAEMON_SOCKET_PATH.name]=this.host.socketPath;if(o.toolOutputsDir)n[G4]=o.toolOutputsDir;return n}withDaemonOptions(o,n){let a=[...o.args,`${ff}=${encodeURIComponent(this.host.socketPath)}`];return Qe(a,n),Ze(a,n),et(a,n),tt(a,n),rt(a,n),a.push(...EQ(n)),{...o,args:a}}resolveLaunchCommand(){return this.host.launchCommandResolver?.()??this.host.launcher.resolveCommand()}async createDaemonStartupFailure(o,n){let a=new t(await this.formatDaemonStartupFailure(o,n));if(this.isIncompleteExtractionStartupSummary(o))a.code=Kb;return a}async createLockHolderStartupFailure(o){let a=o??await this.host.getLockHolderStartupLogPath();if(!a)return new t("Another process is starting the daemon but it failed to become ready; the startup lock did not contain a usable holder PID for diagnostics.");return new t(await this.formatDaemonStartupFailure("Another process is starting the daemon but it failed to become ready",a))}daemonLaunchLogPath(){return Ye(LK(),`daemon-launch-${process.pid}.log`)}async createDaemonExitFailure(o,n,a){let s=o===null?"unknown":o.toString(),c=n?`, signal ${n}`:"",d=o===WO?this.formatIncompleteExtractionStartupSummary(s,c):`Daemon subprocess exited before becoming ready (exit code ${s}${c})`;return this.createDaemonStartupFailure(d,a)}formatIncompleteExtractionStartupSummary(o,n){return`Daemon subprocess exited before becoming ready (exit code ${o}${n}): database startup migrations reported an incomplete package extraction (${Kb}). remove the incomplete extraction directory and re-run; a fresh extraction from the healthy shared cache should start normally.`}isIncompleteExtractionStartupSummary(o){return o.includes(`exit code ${WO}`)&&o.includes("incomplete package extraction")}isIncompleteExtractionStartupError(o){return o?.code===Kb}describeError(o){return r(o)}async formatDaemonStartupFailure(o,n){let a=await this.readDaemonStartupLogExcerpt(n);if(a.length===0){if(n===Xe)return`${o}
4
+ Daemon stderr was relayed to the configured process sink; file capture is disabled.`;return`${o}
5
+ Logs: ${n} (empty)`}return[o,`Logs: ${n}`,`${this.daemonLaunchLogLabel()} (last ${ye} bytes):`,a].join(`
6
+ `)}daemonLaunchLogLabel(){return qf()==="file"?"Daemon stdout/stderr log excerpt":"Daemon stdout log excerpt; stderr was relayed to the configured process sink"}async readDaemonStartupLogExcerpt(o){let n;try{n=await ze(o,"r");let{size:a}=await n.stat(),s=Math.max(0,a-ye),c=a-s,d=Buffer.alloc(c),{bytesRead:m}=await n.read(d,0,c,s),u=d.subarray(0,m).toString("utf-8").trim();return s>0?`...${u}`:u}catch(a){return`Unable to read daemon stdout/stderr log: ${r(a)}`}finally{await n?.close()}}}function f(o){if(H8()){e.info(o);return}process.stderr.write(o+`
7
+ `)}function be(o){let n=o.stderr;if(!n)return;n.on("data",(a)=>{if(!process.stderr.write(a))n.pause(),process.stderr.once("drain",()=>n.resume())}),n.unref?.()}var ye=4000;function Qe(o,n){if(n.port)o.push("--port",n.port.toString());if(n.host)o.push("--host",n.host);if(F(o,[[n.strictPort,"--strict-port"],[n.debug,"--debug"],[n.debugPerf,"--debug-perf"]]),n.planExecutionLockScope)o.push("--plan-execution-lock-scope",n.planExecutionLockScope);if(n.runnerReadinessTimeoutMs!==void 0)o.push(sb,n.runnerReadinessTimeoutMs.toString())}function Ze(o,n){if(n.videoQualityPreset)o.push("--video-quality",n.videoQualityPreset);if(n.videoTargetBitrateKbps!==void 0)o.push("--video-target-bitrate-kbps",n.videoTargetBitrateKbps.toString());if(n.videoMaxThroughputMbps!==void 0)o.push("--video-max-throughput-mbps",n.videoMaxThroughputMbps.toString());if(n.videoFps!==void 0)o.push("--video-fps",n.videoFps.toString());if(n.videoFormat)o.push("--video-format",n.videoFormat);if(n.videoMaxArchiveSizeMb!==void 0)o.push("--video-archive-size-mb",n.videoMaxArchiveSizeMb.toString())}function et(o,n){F(o,[[n.networkMockable,"--network-mockable"],[n.embeddedSdk,"--embedded-sdk"]]);for(let a of n.enabledTools??[])o.push("--enable-tool",a);for(let a of n.disabledTools??[])o.push("--disable-tool",a);if(n.dismissKeyboardAfterInput)o.push("--dismiss-keyboard-after-input");if(n.eventAllMarkers&&n.eventAllMarkers.length>0)o.push(Yc,n.eventAllMarkers.join(","));else if(n.eventAllMarkersCliOverride)o.push(`${Yc}=`)}function tt(o,n){F(o,[[n.noUiPerfMode,"--no-ui-perf-mode"],[n.noNavigationScreenshots,"--no-navigation-screenshots"],[n.noWaitForPollingOverhead,"--no-waitfor-polling-overhead"],[n.noOcclusion,"--no-occlusion"],[n.noA11yIncludeNotImportantViews,"--no-include-not-important-views"],[n.noA11yReportViewIds,"--no-report-view-ids"],[n.noA11yRetrieveInteractiveWindows,"--no-retrieve-interactive-windows"]])}function rt(o,n){if(F(o,[[n.memPerfAudit,"--mem-perf-audit"],[n.accessibilityAudit,"--accessibility-audit"]]),n.accessibilityLevel)o.push("--a11y-level",n.accessibilityLevel);if(n.accessibilityFailureMode)o.push("--a11y-failure-mode",n.accessibilityFailureMode);if(n.accessibilityMinSeverity)o.push("--a11y-min-severity",n.accessibilityMinSeverity);F(o,[[n.accessibilityUseBaseline,"--a11y-use-baseline"],[n.predictiveUi,"--predictive-ui"],[n.rawElementSearch,"--raw-element-search"],[n.skipCtrlProxyDownload,"--skip-ctrl-proxy-download"],[n.toolCallRecording,"--tool-call-recording"]])}function F(o,n){for(let[a,s]of n)if(a)o.push(s)}import{existsSync as ot}from"fs";class K{host;constructor(o){this.host=o}async waitForReady(o,{signal:n,shouldContinueWaiting:a=()=>!0,maxProbeDurationMs:s,launchedProcess:c}={}){return c?this.waitForLaunchedProcessReady(c.pid,o,n??new AbortController().signal,c.launchNonce):this.waitForObservedDaemonReady(o,n,a,s)}async waitForObservedDaemonReady(o,n,a,s){let c=this.host.timer.now(),d=c+o,m=100,u=0,p=!1;while(this.host.timer.now()<d){if(n?.aborted)return!1;u++;let D=a();if(this.host.socketPathObservable()){p=!0;let S=await this.probeObservedSocketWithWatchdog(D,d,n,{shouldContinueWaiting:a,maxProbeDurationMs:s});if(S==="ready")return f(`Daemon readiness probe succeeded after ${this.host.timer.now()-c}ms (${u} polls; socket observed)`),!0;if(S==="aborted")return f(`Daemon readiness probe aborted after ${this.host.timer.now()-c}ms (${u} polls); no longer waiting on the process bringing up the daemon`),!1}if(!D)return f(`Daemon readiness wait abandoned after ${this.host.timer.now()-c}ms (${u} polls); the process it was waiting on is no longer running`),!1;let b=this.host.remainingTime(d);if(b===0)break;await this.host.sleepUnlessAborted(Math.min(100,b),n)}return f(`Daemon readiness probe timed out after ${this.host.timer.now()-c}ms (${u} polls; socket ${p?"observed":"not observed"})`),!1}async probeObservedSocketWithWatchdog(o,n,a,{shouldContinueWaiting:s,maxProbeDurationMs:c}){let d=o?Math.min(n,c===void 0?n:this.host.timer.now()+c):Math.min(n,this.host.timer.now()+E),m=o?this.startLivenessWatchdog(a,s):void 0;try{return await this.probeObservedSocket(d,m?.signal??a)}finally{m?.dispose()}}async probeObservedSocket(o,n){if(await this.host.verifyDaemonConnection(this.host.remainingTime(o),n))return"ready";if(n?.aborted)return"aborted";return"unready"}startLivenessWatchdog(o,n){let a=new AbortController;if(o?.aborted)a.abort();let s=()=>a.abort();o?.addEventListener("abort",s,{once:!0});let c=this.host.timer.setInterval(()=>{try{if(!n())a.abort()}catch(d){e.debug(`[DaemonManager] liveness watchdog predicate threw: ${r(d)}`)}},ct);return{signal:a.signal,dispose:()=>{this.host.timer.clearInterval(c),o?.removeEventListener("abort",s)}}}async tryJoinPeerDaemonAfterSpawnExit(o){let n=this.host.isIsolatedSocketNamespace()?Math.min(o,it):o,a=this.host.timer.now()+n,s,c=this.host.timer.now();while(this.host.remainingTime(a)>0){let d=Math.min(E,this.host.remainingTime(a));if(d>0&&await this.host.peerSocketReachability.probe(this.host.socketPath,d)==="answered")return f("Reusing a peer daemon that became ready after our launch exited"),!0;let m=this.host.remainingTime(a);if(m===0)return!1;if(s===void 0||this.host.timer.now()>=c)s=await this.hasComingUpPeerDaemon(m),c=this.host.timer.now()+at;if(!s){let p=Math.min(E,this.host.remainingTime(a));if(p>0&&await this.host.peerSocketReachability.probe(this.host.socketPath,p)==="answered")return f("Reusing a peer daemon that became ready after our launch exited"),!0;return!1}let u=this.host.remainingTime(a);if(u===0)break;await this.host.timer.sleep(Math.min(nt,u))}return!1}async hasComingUpPeerDaemon(o){try{return(await this.host.findNamespaceDaemonProcessRecords(o)).length>0}catch(n){return e.warn(`[DaemonManager] peer-daemon discovery failed during post-exit rejoin; treating as no peer coming up: ${r(n)}`,n),!1}}async waitForExistingDaemon(o){let a=this.host.timer.now()+o,s=100;while(this.host.timer.now()<a){if(await this.host.verifyDaemonConnection(this.host.remainingTime(a)))return!0;let c=this.host.remainingTime(a);if(c===0)break;await this.host.timer.sleep(Math.min(100,c))}return!1}sleepUnlessAborted(o,n){if(!n)return this.host.timer.sleep(o);if(n.aborted)return Promise.resolve();return new Promise((a)=>{let s=()=>{n.removeEventListener("abort",c),a()},c=()=>{this.host.timer.clearTimeout(d),s()},d=this.host.timer.setTimeout(s,o);n.addEventListener("abort",c,{once:!0})})}remainingTime(o){return Math.max(0,o-this.host.timer.now())}socketPathObservable(){return this.host.platform==="win32"||ot(this.host.socketPath)}isIsolatedSocketNamespace(){return this.host.pidFilePath!==yz||this.host.socketPath!==RB}async verifyDaemonConnection(o,n,a){let s=this.host.timer.now()+o;for(let c=1;c<=Rz;c++){let d=this.host.remainingTime(s);if(d===0||n?.aborted)return!1;let m=this.host.createClient(a?{clientIdentity:null}:void 0);try{return await this.connectReadinessProbe(m,d,n,a)}catch(p){e.debug(`Daemon socket readiness probe failed (attempt ${c}/${Rz}): ${r(p)}`)}finally{try{await m.close()}catch(p){e.debug(`Failed to close daemon readiness probe client: ${r(p)}`)}}let u=this.host.remainingTime(s);if(c<Rz&&u>0)await this.host.sleepUnlessAborted(Math.min(ene,u),n)}return!1}async connectReadinessProbe(o,n,a,s){let c=new AbortController,d=()=>c.abort();a?.addEventListener("abort",d,{once:!0});try{return await l((async()=>{let m=this.host.timer.now()+n;if(await o.connect(n,c.signal),!s)return!0;let u=this.host.remainingTime(m);if(u===0||c.signal.aborted)return!1;let p=await o.callDaemonMethod("ide/status",{},{timeoutMs:u,signal:c.signal,abortMode:"request"}),D=fV(p,this.host.socketPath),b=dt(s,D);if(b)e.debug(`Launched daemon readiness identity mismatch: ${b}`);return b===void 0})(),{timer:this.host.timer,timeoutMs:n,label:"Daemon readiness probe",timeoutError:()=>Error(`Daemon readiness probe timed out after ${n}ms`),onTimeout:()=>c.abort()})}finally{c.abort(),a?.removeEventListener("abort",d)}}async waitForLaunchedProcessReady(o,n,a,s){let c=this.host.timer.now(),d=c+n,m=0;while(!a.aborted&&this.host.remainingTime(d)>0){if(m++,await this.isLaunchedProcessReady(o,Math.min(1000,this.host.remainingTime(d)),a,s))return f(`Launched daemon readiness succeeded after ${this.host.timer.now()-c}ms (${m} polls)`),!0;await this.host.sleepUnlessAborted(Math.min(100,this.host.remainingTime(d)),a)}return f(`Launched daemon readiness ${a.aborted?"abandoned":"timed out"} after ${this.host.timer.now()-c}ms (${m} polls)`),!1}async isLaunchedProcessReady(o,n,a,s){if(o===void 0)return e.debug("Launched daemon readiness identity mismatch: spawned pid missing"),!1;let c=await this.host.lifecycleStatus(),d=s===void 0?c.pid===o:c.launchNonce===s;if(!c.running||!d){let m=s===void 0?"spawned pid":"launch nonce";return e.debug(`Launched daemon readiness identity mismatch: ${c.running?m:"not running"}`),!1}return this.verifyDaemonConnection(n,a,c)}}var E=1000,nt=100,at=1000,it=2000,ct=100;function dt(o,n){if(n.pid!==o.pid)return"pid";if(o.startedAt===void 0||n.startedAt!==o.startedAt)return"startedAt";if(Dr(n)!==Dr(o))return"generation token";if(o.launchNonce!==void 0&&n.launchNonce!==o.launchNonce)return"launch nonce";return}class q{host;heldLockLogPath;constructor(o){this.host=o}acquireLock(){let o=this.host.daemonLaunchLogPath(),n=ti(this.host.lockFilePath,{isProcessRunning:(a)=>this.host.isProcessRunning(a),ownerGeneration:this.host.lockOwnerGenerationProbe,ownerToken:this.host.startupLockOwnerToken,metadata:Buffer.from(o,"utf8").toString("base64url")});return this.heldLockLogPath=n?o:void 0,n}releaseLock(){Wn(this.host.lockFilePath,process.pid,this.host.startupLockOwnerToken),this.heldLockLogPath=void 0}async startByAwaitingLockHolder(o,n,a){let s=null,c=this.host.readStartupLockHolder(),d=this.host.timer.now()+on;while(this.host.remainingTime(d)>0){this.host.throwIfRecoveryCancelled(n);let u=this.host.remainingTime(d);f("Another process is starting the daemon, waiting..."),s=await this.host.getLockHolderStartupLogPath()??s,this.host.throwIfRecoveryCancelled(n),c=this.host.readStartupLockHolder();let p=await this.waitForStartupLockHolder(d,u,c,n);if(this.host.throwIfRecoveryCancelled(n),p)return f("Daemon started by another process"),"joined";if(this.host.throwIfRecoveryCancelled(n),this.host.acquireLock()){f("Previous lock holder failed, taking over daemon start...");try{return this.host.throwIfRecoveryCancelled(n),await(a?.()??this.host.startUnlocked(o,n))}finally{this.host.releaseLock()}}this.host.throwIfRecoveryCancelled(n);let D=this.host.readStartupLockHolder();if(D.livePid===void 0||this.isSameStartupLockHolder(D,c))break;c=D,f("Startup lock reclaimed by another process, waiting again...")}let m=Math.min(E,this.host.remainingTime(d));if(this.host.throwIfRecoveryCancelled(n),await this.confirmLockFollowerReady(m,c.recovering===!0,n))return this.host.throwIfRecoveryCancelled(n),f("Daemon became ready before reporting startup failure"),"joined";throw await this.host.createLockHolderStartupFailure(s)}async waitForStartupLockHolder(o,n,a,s){Object.assign(a,await this.host.readSettledStartupLockHolder(o,s));let c=()=>this.isStillWaitingOnStartupLockHolder(a);if(!a.recovering){let d=await this.host.waitForReady(Math.min(n,this.host.remainingTime(o)),{signal:s,shouldContinueWaiting:c,maxProbeDurationMs:J}),m=await this.host.readSettledStartupLockHolder(o,s);if(a.recovering=m.recovering,!a.recovering)return d}return this.waitForPublishedLockHolderIdentity(o,c,s)}async readSettledStartupLockHolder(o,n){let a=this.host.readStartupLockHolder();for(let s=0;a.metadataPending&&s<3;s++){if(this.host.remainingTime(o)<=0)break;await this.host.sleepUnlessAborted(Math.min(1,this.host.remainingTime(o)),n),a=this.host.readStartupLockHolder()}return a}async confirmLockFollowerReady(o,n,a){if(o<=0||!this.host.socketPathObservable())return!1;return n?this.waitForPublishedLockHolderIdentity(this.host.timer.now()+o,()=>!1,a):this.host.verifyDaemonConnection(o)}async authenticateLockFollowerOwner(o){let n=Math.min(J,this.host.remainingTime(o));if(n<=0||!this.host.identityRecoveryIO.socketExists())return{running:!1};let a=Error("Lock follower owner probe timed out");try{return await l(this.host.authenticateSocketOwner(),{timer:this.host.timer,timeoutMs:n,label:"Lock follower owner probe",timeoutError:()=>a})}catch(s){if(s===a)return{running:!1};throw s}}async waitForPublishedLockHolderIdentity(o,n,a){while(this.host.remainingTime(o)>0){this.host.throwIfRecoveryCancelled(a);let s=await this.authenticateLockFollowerOwner(o);if(s.running&&this.host.hasPublishedRecoveryIdentity(s))return!0;if(!n())return!1;await this.host.sleepUnlessAborted(Math.min(100,this.host.remainingTime(o)),a)}return!1}readStartupLockHolder(){let o;try{o=ve(this.host.lockFilePath,"utf-8").trim()}catch(d){return e.debug(`[DaemonManager] Startup lock unreadable while waiting for holder: ${this.host.describeError(d)}`),{present:!1,livePid:void 0,token:void 0}}if(o.length===0)return{present:!0,livePid:void 0,token:void 0};let{pid:n,token:a,metadata:s,generation:c}=Es(o);if(!Number.isSafeInteger(n)||n<=0)return{present:!0,livePid:void 0,token:a};return this.host.isProcessRunning(n)&&AP(this.host.lockOwnerGenerationProbe,n,c)!=="different"?{present:!0,livePid:n,token:a,...this.startupLockMetadata(s)}:{present:!1,livePid:void 0,token:a}}isSameStartupLockHolder(o,n){if(o.token!==void 0&&n.token!==void 0)return o.token===n.token;if(o.token!==n.token)return!1;return o.livePid!==void 0&&o.livePid===n.livePid}isStartupLockHeldByLiveProcess(){return this.host.readStartupLockHolder().present}isStillWaitingOnStartupLockHolder(o){let n=this.host.readStartupLockHolder();return n.present&&(n.livePid===void 0||o.livePid===void 0||this.isSameStartupLockHolder(n,o))}async waitForLockHolderReadiness(o){let n=this.host.timer.now()+o,a=this.host.readStartupLockHolder();while(this.host.remainingTime(n)>0){if(await this.host.waitForReady(this.host.remainingTime(n),{shouldContinueWaiting:()=>this.isStillWaitingOnStartupLockHolder(a),maxProbeDurationMs:J}))return!0;let d=this.host.readStartupLockHolder();if(d.livePid===void 0||this.isSameStartupLockHolder(d,a))break;a=d}let s=Math.min(E,this.host.remainingTime(n));if(s>0&&this.host.socketPathObservable()&&await this.host.verifyDaemonConnection(s))return!0;return!1}startupLockMetadata(o){if(!o?.startsWith("{"))return{logPath:Buffer.from(o??"","base64url").toString("utf8")};try{let n=JSON.parse(o);if(typeof n==="object"&&n!==null&&"logPath"in n)return{logPath:typeof n.logPath==="string"?n.logPath:"",recovering:"recovering"in n&&n.recovering===!0}}catch(n){return e.debug("Startup lock metadata is not yet readable",n),{logPath:"",recovering:!0,metadataPending:!0}}return{logPath:""}}markStartupLockRecovering(){let o=this.host.readStartupLockHolder();if(o.livePid!==process.pid||o.token!==this.host.startupLockOwnerToken)return;let{noFollow:n,unsafeWriteMask:a}=process.platform==="win32"?{noFollow:0,unsafeWriteMask:0}:{noFollow:Pe.O_NOFOLLOW,unsafeWriteMask:18},s;try{s=lt(this.host.lockFilePath,Pe.O_RDWR|n,384)}catch(c){e.warn("Failed to safely open startup lock for identity recovery",c);return}try{let c=pt(s),d=process.getuid?.();if(!c.isFile()||d!==void 0&&c.uid!==d||(c.mode&a)!==0){e.warn("Refusing unsafe startup lock for identity recovery",{uid:c.uid,mode:c.mode,regularFile:c.isFile()});return}let m=ve(s,"utf8"),{pid:u,token:p,metadata:D,generation:b}=Es(m.trim());if(u!==process.pid||p!==this.host.startupLockOwnerToken)throw new t("Startup lock ownership changed before identity recovery");let S=JSON.stringify({logPath:this.startupLockMetadata(D).logPath,recovering:!0}),v=fy(u,p,S,b);ht(s,v.padEnd(Buffer.byteLength(m)),0,"utf8")}finally{ut(s)}}async getLockHolderStartupLogPath(){try{let o=await mt(this.host.lockFilePath,"utf-8"),{pid:n,metadata:a}=Es(o.trim());if(!Number.isSafeInteger(n)||n<=0)return null;if(!a)return null;let{logPath:s}=this.startupLockMetadata(a);if(!yt(s)||ft(s)!==`daemon-launch-${n}.log`)return null;return s}catch(o){return e.debug(`[DaemonManager] Unable to read startup lock holder diagnostics: ${this.host.describeError(o)}`),null}}}var J=1000;import{basename as Ot,isAbsolute as Et}from"path";import{devNull as Lt}from"os";var gt=g({pid:T().int().positive().optional(),startedAt:T().finite().optional(),processGenerationToken:y().optional()}),bt=g({key:gt,attempts:T().int().positive().safe(),firstDeferredAtMs:T().min(-8640000000000000).max(8640000000000000)}),St=3,vt=60000,Rt=600000;function wt(o,n,a){let s=a-n.firstDeferredAtMs;return o==="active_operations"?s>=Rt:n.attempts>=St||s>=vt}function C({ledger:o,incumbent:n,kind:a,original:s,nowMs:c,subject:d}){let m=o.recordDeferral({pid:n.pid,startedAt:n.startedAt,processGenerationToken:Dr(n)},c);if(!wt(a,m,c))return s;let u=d==="older daemon"?"takeover":"restart",p=`${d} pid ${n.pid} (version ${n.version??"unknown"}) has deferred this ${u} ${m.attempts} times since ${new Date(m.firstDeferredAtMs).toISOString()} (${s.message}); `+`it is never stopped automatically \u2014 run \`bunx ${zs()} --daemon restart\` to replace it once no device operation is active`;return e.warn(p),new Or(p)}function Re(o,n){return o.pid===n.pid&&o.startedAt===n.startedAt&&o.processGenerationToken===n.processGenerationToken}class z{store;unpersisted;constructor(o){this.store=o}recordDeferral(o,n){let a=this.unpersisted&&Re(this.unpersisted.record.key,o)?this.unpersisted:void 0,s=this.previousProgress(o,a),c={key:{...o},attempts:(s?.attempts??0)+1,firstDeferredAtMs:s?.firstDeferredAtMs??n};try{this.store.write(JSON.stringify(c))}catch(d){return e.warn(`Failed to persist takeover deferral ledger: ${r(d)}`,d),this.unpersisted={record:c,attempts:(a?.attempts??0)+1},{attempts:c.attempts,firstDeferredAtMs:c.firstDeferredAtMs}}return this.unpersisted=void 0,{attempts:c.attempts,firstDeferredAtMs:c.firstDeferredAtMs}}previousProgress(o,n){let a=this.read();if(!a||!Re(a.key,o))return n?.record;return{attempts:a.attempts+(n?.attempts??0),firstDeferredAtMs:Math.min(a.firstDeferredAtMs,n?.record.firstDeferredAtMs??a.firstDeferredAtMs)}}clear(){this.unpersisted=void 0,this.store.clear()}read(){try{let o=this.store.read();if(o===null)return;let n=JSON.parse(o),a=bt.safeParse(n);return a.success?a.data:void 0}catch(o){e.warn(`Failed to read takeover deferral ledger: ${r(o)}`,o);return}}}var we=h.DAEMON_LAUNCH_CHECKOUT_VERSION.name;class Y{host;runningRestartOptions=new WeakSet;constructor(o){this.host=o}async start(o={}){let n=!this.runningRestartOptions.has(o);if(!this.host.acquireLock())return await this.host.startByAwaitingLockHolder(o,void 0,()=>this.host.startUnlocked(o,void 0,n));try{return await this.host.startUnlocked(o,void 0,n)}finally{this.host.releaseLock()}}async startWithRunningOptions(o){this.runningRestartOptions.add(o);try{return await this.host.start(o)}finally{this.runningRestartOptions.delete(o)}}async inheritExitSettings(o){let n=he(this.host.socketPath,this.host.seams.exitRecordFileSystem),a=fe(o,n,this.host.timer.now(),{ttl:pe,buildId:this.host.seams.currentBuildId()});if(a.outcome==="stale"||a.outcome==="build-mismatch")e.info(`Ignoring daemon exit record: ${a.outcome}`);if(a.outcome!=="inherited"||!n)return a.options;let s=a.options,c="";if(a.inheritedPort&&s.port!==void 0){if(s.strictPort=await this.host.seams.portFreeProbe(s.port),!s.strictPort)c="; previous port is busy, binding without strictness"}let d=Object.entries(s).filter(([m])=>m!=="port").map(([m,u])=>u===!0?m:`${m}=${JSON.stringify(typeof u==="string"&&Et(u)?Ot(u):u)}`).join(" ");return f(`Inheriting daemon port ${s.port??"default"} after ${n.reason}; flags: ${d||"none"}${c}`),s}async startUnlocked(o,n,a=!0){o=os(o);let s=this.host.timer.now()+on;if(!Sl())await bl();let c=await this.admitStart(o,n,a,s);if("done"in c)return c.done;return this.launchDaemon(c.options,c.inheritExitRecord,s,n)}async admitStart(o,n,a,s){let c=await this.host.lifecycleStatus();if(this.host.throwIfRecoveryCancelled(n),c.running&&!await this.host.verifyDaemonGenerationBeforeSignal(this.host.daemonProcessRecordFromStatus(c),void 0,"Daemon start"))c={running:!1};if(!c.running&&c.recovery)return{done:await this.recoverOrJoinNamespaceIdentity(c,s)};if(c.running){let d=await this.takeOverOlderDaemon(c,o);if("done"in d)return d;o=d.options,a=!1}if(await this.joinLiveDaemonWithoutRecord(o,s,n))return{done:"joined"};return{options:o,inheritExitRecord:a}}async recoverOrJoinNamespaceIdentity(o,n){let a=o.recovery?.state==="unauthenticated"?await this.host.probeNamespaceOwner():void 0;if(a?.reportedSocketPath===void 0&&a?.reportedPidFilePath===void 0&&a?.pid!==void 0&&await this.host.waitForExistingDaemon(Math.min(bz,this.host.remainingTime(n))))return"joined";return this.host.startIdentityRecovery(o)}async takeOverOlderDaemon(o,n){if(pne(o.version,di))return f(`Daemon is already running (PID ${o.pid}, port ${o.port})`),{done:"joined"};if(o.startedAt){let s=this.host.timer.now()-o.startedAt;if(s<Pp)throw e.warn(`[DaemonManager] Skipping strictly-older daemon takeover due to cooldown: daemon ${o.version} is ${s}ms old, current version is ${di}`),new Or("restart is in cooldown")}if(!await this.prepareOlderDaemonRestart(o))return{done:"joined"};this.host.takeoverDeferrals.clear();let a=os(Object.fromEntries(Object.entries(n).filter(([,s])=>s!==void 0)));return n={...os(o.options),...a,strictPort:!0},f(`Detected strictly older AutoMobile daemon version ${o.version} (PID ${o.pid}); stopping it before upgrade...`),await this.host.stopRunningDaemon(o,oo,!1),await this.host.assertNoSurvivingDaemonBeforeRestart(n),await this.host.timer.sleep(vl),{options:n}}async prepareOlderDaemonRestart(o){let n;try{n=await this.host.prepareDaemonForConditionalRestart(o)}catch(c){if(c instanceof Or)this.deferOlderDaemonTakeover(o,"unavailable",c);throw c}if(n.accepted)return!0;if(n.reason==="generation_changed"||n.reason==="restart_pending")return f("Daemon restart is already in progress; joining its successor"),!1;let a=n.reason==="active_operations"?"active_operations":"unavailable",s=n.reason==="active_operations"?"a device operation is active":n.reason==="shutdown_unavailable"?"the daemon could not initiate its own shutdown":"the daemon returned an unrecognized safe-restart admission result";this.deferOlderDaemonTakeover(o,a,new Or(s))}deferOlderDaemonTakeover(o,n,a){throw C({ledger:this.host.takeoverDeferrals,incumbent:o,kind:n,original:a,nowMs:this.host.timer.now(),subject:"older daemon"})}async joinLiveDaemonWithoutRecord(o,n,a){let s=await this.host.findLiveDaemonProcessesForStart(o,n);if(this.host.throwIfRecoveryCancelled(a),s.length>0){f(`Found ${s.length} live auto-mobile daemon process(es) without a usable PID record; waiting for one to become ready...`);for(let m of s)f(` - PID ${m}`);let c=Math.min(bz,this.host.remainingTime(n)),d=await this.host.waitForExistingDaemon(c);if(this.host.throwIfRecoveryCancelled(a),d)return f("Reusing existing responsive daemon"),!0;throw new t(`Found live AutoMobile daemon process(es) (${s.join(", ")}) but none became reachable within ${c}ms. Refusing to terminate a live daemon during start; inspect it or run \`bunx ${zs()} --daemon restart\` explicitly.`)}return!1}async stampLaunchCheckoutVersion(o){delete o[we];let n;try{n=await this.host.seams.probeLaunchCheckoutVersion()}catch(a){e.warn("Checkout version probe before daemon launch failed",a);return}if(MK(n))o[we]=n}async launchDaemon(o,n,a,s){if(n)o=await this.host.inheritExitSettings(o);else O(this.host.socketPath,this.host.seams.exitRecordFileSystem);f("Starting AutoMobile daemon...");let c=this.host.withDaemonOptions(this.host.resolveLaunchCommand(),o),d=this.host.daemonLaunchEnvironment(o),m=qf(d),u=m!=="stderr",p=u?this.host.heldLockLogPath??this.host.daemonLaunchLogPath():Lt;if(d[Jre]=u?p:"",await this.stampLaunchCheckoutVersion(d),u)Jae(),$K(),une(p);let D=this.host.seams.launchLogFileSystem.openSync(p,"w",384);try{await this.host.launchWithExtractionRetry({options:o,childEnv:d,logSink:m,capturesLaunchOutput:u,logFd:D,logPath:p},c,a,s)}catch(S){this.host.throwIfRecoveryCancelled(s);let v=Math.min(bz,this.host.remainingTime(a)-At);if(v>0&&await this.host.tryJoinPeerDaemonAfterSpawnExit(v))return f("A peer daemon became ready on the shared socket after our launch exited; joining it"),"joined";throw S}finally{this.host.seams.launchLogFileSystem.closeSync(D)}let b=await this.host.lifecycleStatus();return f(`Daemon started successfully (PID ${b.pid}, port ${b.port})`),f(`Socket: ${b.socketPath}`),f(`Logs: ${p}`),"started"}}var At=2000;import{readFile as Wt}from"fs/promises";import{createHmac as ke,timingSafeEqual as Tt}from"crypto";var p4=h.DAEMON_LIVE_ACCEPTANCE_STARTUP_SECRET.name;function Oe(o){let n=Dr(o);if(typeof o.pid!=="number"||typeof o.startedAt!=="number"||typeof o.version!=="string"||typeof o.buildId!=="string"||typeof o.entryScript!=="string"||o.processGenerationToken!==void 0&&typeof o.processGenerationToken!=="string"||o.processGenerationTokenUtc!==void 0&&typeof o.processGenerationTokenUtc!=="string")return;return{pid:o.pid,startedAt:o.startedAt,...n===void 0?{}:{processGenerationToken:n},version:o.version,buildId:o.buildId,entryScript:o.entryScript}}function Ee(o){return["auto-mobile-live-acceptance-capability-v1",o.pid,o.startedAt,o.processGenerationToken??"",o.version,o.buildId,o.entryScript].join("\x00")}function Ft(o,n){return ke("sha256",o).update(Ee(n)).digest("base64url")}function X(o,n,a){return ke("sha256",o).update(`${Ee(n)}\x00${Fr(a)}`).digest("base64url")}function TZ(o,n,a,s){if(!o||typeof s!=="string")return!1;let c=Buffer.from(a===void 0?Ft(o,n):X(o,n,a)),d=Buffer.from(s);return d.length===c.length&&Tt(d,c)}function lq(o=process.env){let n=o[p4];return n&&n.length>=32?n:void 0}function k(o){return o==="joined"?"joined":"restarted"}function M(o,n){return{...U(o,n),strictPort:!0}}async function Le(o,n={},a){o.log("Restarting daemon...");let s=a!==void 0&&o.isRecoveryOwnerReference(a),c=s?await o.probeRecoveryOwner():await o.lifecycleStatus();if(s&&!o.isRecoveryOwner(c))throw new Or("Provider identity changed before replacement");if(s&&o.hasPublishedRecoveryIdentity(c))return"joined";let d=os({...c.options,...c.port===void 0?{}:{port:c.port}}),m=os(Object.fromEntries(Object.entries(n).filter(([,p])=>p!==void 0))),u=M(d,m);if(a&&!o.isSameDaemonGeneration(c,a))return o.log("Daemon generation changed before restart; joining the current generation"),"joined";if(a)return _t(o,c,a,{options:u,recovering:s});return Ct(o,c,u)}async function Ct(o,n,a){if(await o.awaitRestartCleanup([()=>n.running?o.stop(oo,n):void 0,()=>o.stopNamespaceOrphansForExplicitRestart(n.pid)]),n.pid!==void 0&&o.isProcessRunning(n.pid))throw new t("Restart could not confirm the namespace's previous daemon exited; refusing to start a replacement.");await o.assertNoSurvivingDaemonBeforeRestart(a),await o.sleep(vl);let s=n.running?await o.startWithRunningOptions(a):await o.start(a),c=o.recordedStatus();if(n.running&&c.pid===n.pid&&!o.isConfirmedDifferentDaemonGeneration(o.daemonProcessRecordFromStatus(n),o.daemonProcessRecordFromStatus(c)))throw new t("Restart did not replace the namespace's previous daemon generation.");return k(s)}async function It(o,n,a){let s;try{s=a?await o.prepareIdentityRecoveryRestart(n):await o.prepareDaemonForConditionalRestart(n)}catch(m){if(m instanceof Or)throw C({ledger:o.takeoverDeferrals,incumbent:n,kind:m.refusalReason==="active_operations"?"active_operations":"unavailable",original:m,nowMs:o.now(),subject:"daemon"});throw m}if(s.accepted)return!0;if(s.reason==="generation_changed"||s.reason==="restart_pending")return!1;let c=s.reason==="active_operations"?"active_operations":"unavailable",d=s.reason==="active_operations"?"a device operation is active":s.reason==="shutdown_unavailable"?"the daemon could not initiate its own shutdown":"the daemon returned an unrecognized safe-restart admission result";throw C({ledger:o.takeoverDeferrals,incumbent:n,kind:c,original:new Or(d),nowMs:o.now(),subject:"daemon"})}async function _t(o,n,a,{options:s,recovering:c}){if(!await It(o,a,c))return o.log("Daemon restart is already in progress; joining its successor"),"joined";if(o.takeoverDeferrals.clear(),n.running)await o.stopRunningDaemon(n,oo,!1);await o.sleep(vl);let d=c?await o.startUnlocked(s,void 0,!n.running):n.running?await o.startWithRunningOptions(s):await o.start(s);return k(d)}async function Ae(o,n,a){if(!a)throw new t("restart-admitted requires a maintenance admission token.");if(!o.acquireLock())throw new Or("another daemon lifecycle transition is in progress");try{return await Mt(o,n,a)}finally{o.releaseLock()}}async function Mt(o,n,a){let s=await o.lifecycleStatus();if(!s.running)throw new t("restart-admitted requires the daemon generation that admitted maintenance to still be running.");let c=await o.admitMaintenanceRestart(s,a);if(!c.accepted)throw new Or(`maintenance admission is no longer valid (${c.reason??"unknown"})`);let d=M(os(s.options),os(Object.fromEntries(Object.entries(n).filter(([,m])=>m!==void 0))));return await o.stopRunningDaemon(s,oo,!1),await o.sleep(vl),k(await o.startUnlocked(d,void 0,!1))}async function Te(o,n){let a=lq();if(!a)throw new t("restart-acceptance-session requires a live-acceptance daemon startup capability.");if(!o.acquireLock())throw new t("restart-acceptance-session could not acquire the daemon startup lock.");try{return await Nt(o,n,a)}finally{o.releaseLock()}}async function Nt(o,n,a){let s=await o.lifecycleStatus();if(!s.running)throw new t("restart-acceptance-session requires the admitted daemon generation to be running.");let c=Oe(s);if(!c)throw new t("restart-acceptance-session requires the admitted daemon generation identity.");let d=o.createClient({clientIdentity:null}),m,u=!1,p,D=!1;try{if(await d.connect(),m=await xt(o,d,s,{generation:c,scope:n,startupSecret:a}),await Gt(o,d,s,m),await Ut(o,s,c)){o.signalProcess(s.pid,"SIGKILL"),u=!0;let b={pid:s.pid,ppid:0,command:s.entryScript??"",startedAt:s.processStartedAt??s.startedAt,processGenerationToken:Dr(s)},S=await o.waitForStop(s.pid,ik,b);if(D=S.replacedByOtherGeneration,!S.stopped)throw new t(`Acceptance-session restart daemon process ${s.pid} did not exit after SIGKILL.`)}}catch(b){if(p=b,m&&!u)await Ht(o,d,s,m);throw b}finally{await $t(o,d,p)}return await o.cleanupAcceptanceRestartFiles(s,D),await o.sleep(vl),k(await o.startUnlocked({...os(s.options),strictPort:!0},void 0,!1))}async function xt(o,n,a,{generation:s,scope:c,startupSecret:d}){let u=await n.callDaemonMethod(aq,{...a,scope:c,acceptanceCapability:X(d,s,c)});if(u?.accepted!==!0)throw new t(`Daemon declined the acceptance-session restart (${u?.reason??"unknown"}).`);if(!u.restartToken)throw new t("Daemon accepted the acceptance-session restart without a rollback token.");return u.restartToken}async function Gt(o,n,a,s){if((await n.callDaemonMethod(cq,{...a,restartToken:s}))?.committed!==!0)throw new t("Daemon acceptance-session restart admission expired before it could be committed.")}async function Ht(o,n,a,s){try{await n.callDaemonMethod(dq,{...a,restartToken:s})}catch(c){e.warn(`Failed to explicitly roll back acceptance restart admission: ${r(c)}`)}}async function $t(o,n,a){try{await n.close()}catch(s){if(a===void 0)throw s;e.warn(`Failed to close acceptance restart control client after primary failure: ${r(s)}`)}}async function Ut(o,n,a){return o.verifyDaemonGenerationBeforeSignal({pid:a.pid,ppid:0,command:"",startedAt:n.processStartedAt??a.startedAt,processGenerationToken:a.processGenerationToken},void 0,"Live acceptance")}class Z{host;constructor(o){this.host=o}async recoverControlState(o,n,a,s){if(this.host.throwIfRecoveryCancelled(a),!this.host.acquireLock())return k(await this.host.startByAwaitingLockHolder(o,a,async()=>await this.recoverControlStateWhileLocked(o,n,a,s)==="restarted"?"started":"joined"));try{return await this.recoverControlStateWhileLocked(o,n,a,s)}finally{this.host.releaseLock()}}async recoverControlStateWhileLocked(o,n,a,s){if(await n())return this.host.throwIfRecoveryCancelled(a),f("Daemon became healthy during control-state recovery; joining it."),"joined";this.host.throwIfRecoveryCancelled(a);let c=await this.host.lifecycleStatus();this.host.throwIfRecoveryCancelled(a);let d=await this.host.findNamespaceDaemonProcessRecords(this.host.remainingRecoveryTime(s)),m=this.findRecoveryCandidate(c,d);this.assertRecoveryCandidateIsScoped(c,d.map((p)=>p.pid),m),this.host.throwIfRecoveryCancelled(a),await this.stopRecoveryCandidate(m,a,s),this.host.throwIfRecoveryCancelled(a);let u=await this.host.recoveryOptions(c,o);return this.host.throwIfRecoveryCancelled(a),await this.host.assertNoSurvivingDaemonBeforeRestart(u,s),this.host.throwIfRecoveryCancelled(a),await this.host.timer.sleep(vl),this.host.throwIfRecoveryCancelled(a),k(await this.host.startUnlocked(u,a,!c.running))}findRecoveryCandidate(o,n){if(!o.running||o.pid===void 0||o.socketPath!==this.host.socketPath)return;let a=n.find((s)=>s.pid===o.pid);if(!a||!this.host.matchesRecordedDaemonGeneration(o,a))return;return a}matchesRecordedDaemonGeneration(o,n){let a=this.compareRecordedTokens(Dr(o),n.processGenerationToken);if(a!=="incomparable")return a==="same";let s=o.processStartedAt??o.startedAt;return s!==void 0&&n.startedAt!==void 0&&Math.abs(n.startedAt-s)<=Q}matchesObservedDaemonGeneration(o,n){let a=this.compareRecordedTokens(o.processGenerationToken,n.processGenerationToken);if(a!=="incomparable")return o.pid===n.pid&&a==="same";return o.pid===n.pid&&o.startedAt!==void 0&&n.startedAt!==void 0&&Math.abs(n.startedAt-o.startedAt)<=Q}compareRecordedTokens(o,n){if(o===void 0)return"incomparable";return n===void 0?"different":Za(o,n)}isConfirmedDifferentDaemonGeneration(o,n){if(o.pid!==n.pid)return!1;if(o.processGenerationToken!==void 0){if(n.processGenerationToken===void 0)return!1;let a=Za(o.processGenerationToken,n.processGenerationToken);if(a!=="incomparable")return a==="different"}return o.startedAt!==void 0&&n.startedAt!==void 0&&Math.abs(n.startedAt-o.startedAt)>Q}assertRecoveryCandidateIsScoped(o,n,a){if(n.length>0&&(a===void 0||n.length>1))throw new t("Daemon recovery could not correlate the failed control socket with exactly one live AutoMobile daemon process. Refusing to stop an uncorrelated daemon; inspect the namespace PID record and socket before retrying.");if(o.running&&a===void 0)throw new t("Daemon recovery found live PID control metadata that does not match a current AutoMobile daemon process. Refusing to signal a potentially reused PID.")}throwIfRecoveryCancelled(o){if(o?.aborted)throw new t("Daemon recovery deadline elapsed before a safe recovery transition could complete.")}async stopRecoveryCandidate(o,n,a){if(o===void 0)return;this.host.throwIfRecoveryCancelled(n),f(`Repair force-stopping the verified daemon for this control namespace (PID ${o.pid})...`),await this.host.stopUnrecordedDaemonProcess(o,a,n)}remainingRecoveryTime(o){if(o===void 0)return;let n=this.host.remainingTime(o);if(n<=0)throw new t("Daemon recovery deadline elapsed before process-table inspection could complete.");return n}async recoveryOptions(o,n){let a=o.options??await this.readRecoveryOptionsFromPidFile(),s=os(Object.fromEntries(Object.entries(n).filter(([,c])=>c!==void 0&&c!==!1)));return M(os(a),s)}async readRecoveryOptionsFromPidFile(){try{let o=JSON.parse(await Wt(this.host.pidFilePath,"utf-8"));if(!o||typeof o!=="object"||Array.isArray(o))return{};let n=o,a=n.options&&typeof n.options==="object"&&!Array.isArray(n.options)?n.options:{};return{...a,...typeof n.port==="number"&&a.port===void 0?{port:n.port}:{}}}catch(o){return e.debug(`Unable to recover daemon options from PID metadata: ${r(o)}`),{}}}}var Q=2000;import{readFile as Yt}from"fs/promises";import{existsSync as _e}from"fs";import{mkdirSync as jt}from"fs";import{dirname as Vt}from"path";class m4{incumbent=null;supersededOwner=null;contenderEarlyOwner=null;sawLiveContender=!1;deps;constructor(o){this.deps={readPidFile:o?.readPidFile??(()=>_o()),persistPidFile:o?.persistPidFile??qt,isProcessRunning:o?.isProcessRunning??((n)=>st(n,{debugLog:e.debug})),readProcessGenerationToken:o?.readProcessGenerationToken??Ta,selfPid:o?.selfPid??process.pid}}captureIncumbentBeforeOverwrite(){this.incumbent=null,this.supersededOwner=null,this.contenderEarlyOwner=null,this.sawLiveContender=!1;let o=this.deps.readPidFile();if(o&&o.pid!==this.deps.selfPid&&Ce(o)){if(this.incumbent=o,this.isLiveForeign(o))e.info(`Captured live incumbent daemon owner record (pid ${o.pid}) before overwriting it (issue #6232)`);else this.supersededOwner=Kt(o);return}if(!this.isLiveForeign(o)){this.supersededOwner=this.supersededOwnerCarriedBy(o);return}this.sawLiveContender=!0,e.info(`Detected a live hand-launched contender (pid ${o.pid}) mid-startup; failing the lock-less socket bind closed rather than treating its record as the socket owner (issue #6232)`)}asSocketOwnerLiveness(){return{getOwnerStatus:()=>this.getOwnerStatus()}}hasLiveForeignOwner(){return this.sawLiveContender||this.isLiveForeign(this.incumbent)}capturedLiveIncumbentDaemonSessionId(){return this.isLiveForeign(this.incumbent)?this.incumbent.daemonSessionId:void 0}withLiveIncumbent(o){let n=this.capturedLiveIncumbentDaemonSessionId();if(n===void 0||o.has(n))return o;return new Set([...o,n])}supersededOwnerForEarlyRecord(){return this.supersededOwner??void 0}getOwnerStatus(){if(this.sawLiveContender)return"unknown";if(this.incumbent===null)return this.supersededOwnerStatus();return this.isLiveForeign(this.incumbent)?"live":"dead"}supersededOwnerStatus(){let o=this.supersededOwner;if(o===null)return"unknown";return this.isLiveForeign(o)?"live":"dead"}supersededOwnerCarriedBy(o){return o===null?null:Fe(o.supersededOwner)}recordContenderEarlyOwner(o){this.contenderEarlyOwner=o}restoreIncumbentAfterRefusal(){let o=this.incumbent;if(!this.isLiveForeign(o)||!Jt(this.deps.readPidFile(),this.contenderEarlyOwner))return!1;return this.deps.persistPidFile(o),e.info(`Restored live incumbent daemon owner record (pid ${o.pid}) after refusing the bind (issue #6232)`),!0}isLiveForeign(o){return o!==null&&o.pid!==this.deps.selfPid&&this.deps.isProcessRunning(o.pid)&&!cR(o.pid,o,this.deps.readProcessGenerationToken,"the daemon PID record")}}function Kt(o){return{pid:o.pid,..._d(Dr(o))}}function Fe(o){if(typeof o!=="object"||o===null)return null;let n=o,{pid:a}=n;if(typeof a!=="number"||!Number.isInteger(a)||a<=0)return null;return{pid:a,..._d(Dr(n))}}function Jt(o,n){return o!==null&&n!==null&&o.pid===n.pid&&o.startedAt===n.startedAt&&o.socketPath===n.socketPath&&o.dbPath===n.dbPath}function Ce(o){return o.entryScript!==void 0&&o.buildId!==void 0}function Ie(o){return Ce(o)||Fe(o.supersededOwner)!==null}function qt(o){jt(Vt(Sr),{recursive:!0}),lne(Sr,o)}class N extends Error{}class ee{host;constructor(o){this.host=o}async stop(o=oo,n){let a=n??await this.host.status(!1);if(!a.running&&this.host.identityRecoveryIO.socketExists())a=await this.host.authenticateSocketOwner();if(!a.running&&a.recovery)throw new t(`Daemon socket ${this.host.socketPath} is held by a process that could not be authenticated as this namespace's daemon (${a.recovery.state}${a.recovery.reason?`: ${a.recovery.reason}`:""}); nothing was stopped. Run --daemon diagnose to identify the socket owner.`);if(!a.running){await this.host.removeConfirmedDeadPidFile(),O(this.host.socketPath,this.host.seams.exitRecordFileSystem),f("Daemon is not running");return}await this.host.stopRunningDaemon(a,o),O(this.host.socketPath,this.host.seams.exitRecordFileSystem)}async stopRunningDaemon(o,n=oo,a=!0){this.assertDaemonStatusNamespace(o),f(`Stopping daemon (PID ${o.pid})...`);let s=o.pid,c=this.host.daemonProcessRecordFromStatus(o);try{if(a)await this.signalVerifiedDaemonGeneration(c,"SIGTERM",`Daemon generation ${s} exited before stop could signal it.`);let d=await this.host.waitForStop(s,n,c),m=d.replacedByOtherGeneration;if(!d.stopped){if(f("Daemon did not stop gracefully, sending SIGKILL..."),await this.signalVerifiedDaemonGeneration(c,"SIGKILL",`Daemon generation ${s} exited before stop could force-stop it.`),d=await this.host.waitForStop(s,ik,c),m||=d.replacedByOtherGeneration,!d.stopped)throw new t(`Daemon process ${s} did not exit after SIGKILL`)}if(!m)await eb({pidFilePath:this.host.pidFilePath,socketPaths:this.host.cleanupSocketPaths(o.socketPath),expectedPid:s});f("Daemon stopped")}catch(d){await this.handleStopRunningDaemonError(d,o,s)}}daemonProcessRecordFromStatus(o){return{pid:o.pid,ppid:0,command:o.entryScript??"",startedAt:o.processStartedAt??o.startedAt,processGenerationToken:Dr(o)}}assertDaemonStatusNamespace(o){if(o.socketPath!==this.host.socketPath)throw new t("Daemon stop could not attribute the recorded daemon to this socket namespace.")}async signalVerifiedDaemonGeneration(o,n,a){if(!await this.host.verifyDaemonGenerationBeforeSignal(o,void 0,"Daemon stop"))throw new N(a);this.host.processSignaler.signal(o.pid,n)}async handleStopRunningDaemonError(o,n,a){if(o instanceof N){e.debug("Recorded daemon generation died before signalling",o),await this.host.removeConfirmedDeadPidFile(),f(o.message);return}if(o instanceof Error&&o.message.includes("ESRCH")){await eb({pidFilePath:this.host.pidFilePath,socketPaths:this.host.cleanupSocketPaths(n.socketPath),expectedPid:a}),f("Daemon was not running (cleaned up stale PID file)");return}if(o instanceof Error&&o.message.includes("EPERM"))throw new t(`Cannot stop daemon process ${a}: this user cannot signal it (EPERM). Run stop as the process's owning user, or via launchctl/systemd if managed that way.`,{cause:o});throw o}async readConfirmedDeadPidData(){if(!_e(this.host.pidFilePath))return;try{let o=await Yt(this.host.pidFilePath,"utf-8"),n=JSON.parse(o);if(typeof n.pid!=="number"||this.host.isRecordedDaemonRunning(n))return;return n}catch(o){e.warn(`Failed to read PID file during stop(): ${r(o)}`);return}}mustKeepDeadRecordAsSocketOwnerProof(o){return this.host.identityRecoveryIO.socketExists()&&Ie(o)}async removeConfirmedDeadPidFile(){let o=await this.readConfirmedDeadPidData();if(!o||this.mustKeepDeadRecordAsSocketOwnerProof(o))return;let n=this.host.timer.now()+Xt,a=this.host.acquireLock();while(!a&&this.host.remainingTime(n)>0)await this.host.timer.sleep(Math.min(Qt,this.host.remainingTime(n))),a=this.host.acquireLock();if(!a){e.warn("Could not acquire the startup lock to remove a stale PID file during stop(); leaving it for a later safe startup or explicit cleanup to supersede.");return}try{let s=await this.readConfirmedDeadPidData();if(!s||this.mustKeepDeadRecordAsSocketOwnerProof(s))return;await eb({pidFilePath:this.host.pidFilePath,socketPaths:[],expectedPid:s.pid})}catch(s){e.warn(`Failed to remove a confirmed-dead PID file during stop(): ${r(s)}`)}finally{this.host.releaseLock()}}async assertNoSurvivingDaemonBeforeRestart(o,n){let a=(await this.host.findNamespaceDaemonProcessRecords(this.host.remainingRecoveryTime(n))).map((d)=>d.pid);if(a.length>0)throw new t(`Restart could not confirm this namespace's previous daemon stopped: PID(s) ${a.join(", ")} still running in this socket namespace. Verify the \`--daemon-mode\` socket marker, namespace PID record, socket owner and process generation before retrying \`--daemon restart\`.`);let s=o.port??ld,c=o.host??j;if(await this.host.portAvailabilityChecker.isPortFree(s,c,this.host.remainingRecoveryTime(n)))return;throw new t(`Restart stopped this namespace's verified daemon candidates, but replacement port ${s} on ${c} `+"is still in use. Refusing to silently start the replacement daemon on a fallback port \u2014 "+`that is how an orphaned process ends up owning device forwarding while a second daemon reports success. Find and stop whatever still holds port ${s} (it may not be an AutoMobile process this scan could name) and run \`--daemon restart\` again.`)}async stopNamespaceOrphansForExplicitRestart(o){let n=(await this.host.findNamespaceDaemonProcessRecords()).filter((a)=>a.pid!==o);if(n.length===0)return;f(`Explicit restart force-stopping ${n.length} live AutoMobile daemon candidate(s) without this namespace's PID record...`),await this.host.awaitRestartCleanup(n.map((a)=>()=>this.stopExplicitRestartDaemonProcess(a)))}async awaitRestartCleanup(o){let a=(await Promise.allSettled(o.map((s)=>Promise.resolve().then(s)))).find((s)=>s.status==="rejected");if(a)throw a.reason}async stopUnrecordedDaemonProcess(o,n,a){if(!await this.host.verifyDaemonGenerationBeforeSignal(o,n)){f(`Daemon candidate ${o.pid} exited before repair could stop it.`);return}this.host.throwIfRecoveryCancelled(a),f(`Repair stopping the verified daemon for this control namespace (PID ${o.pid})...`);try{this.host.processSignaler.signal(o.pid,"SIGTERM")}catch(s){if(this.isMissingProcessError(s))return;throw new t(`Failed to stop verified daemon process ${o.pid}: ${this.host.describeError(s)}`)}if((await this.host.waitForStop(o.pid,this.stopWaitTimeout(oo,n),o)).stopped)return;if(f(`Verified daemon ${o.pid} did not stop gracefully, sending SIGKILL...`),!await this.host.verifyDaemonGenerationBeforeSignal(o,n)){f(`Daemon candidate ${o.pid} exited before repair could force-stop it.`);return}this.host.throwIfRecoveryCancelled(a);try{this.host.processSignaler.signal(o.pid,"SIGKILL")}catch(s){if(this.isMissingProcessError(s))return;throw new t(`Failed to force-stop verified daemon process ${o.pid}: ${this.host.describeError(s)}`)}if(!(await this.host.waitForStop(o.pid,this.stopWaitTimeout(ik,n),o)).stopped)throw new t(`Verified daemon process ${o.pid} did not exit after SIGKILL`)}async stopExplicitRestartDaemonProcess(o){if(!await this.host.verifyDaemonGenerationBeforeSignal(o,void 0,"Explicit restart")){f(`Daemon candidate ${o.pid} exited before explicit restart could stop it.`);return}f(`Stopping daemon without this namespace's PID record (PID ${o.pid})...`);try{this.host.processSignaler.signal(o.pid,"SIGTERM")}catch(n){if(this.isMissingProcessError(n))return;throw new t(`Failed to stop verified daemon process ${o.pid}: ${this.host.describeError(n)}`)}if((await this.host.waitForStop(o.pid,oo,o)).stopped)return;if(f(`Verified daemon ${o.pid} did not stop gracefully, sending SIGKILL...`),!await this.host.verifyDaemonGenerationBeforeSignal(o,void 0,"Explicit restart")){f(`Daemon candidate ${o.pid} exited before explicit restart could force-stop it.`);return}try{this.host.processSignaler.signal(o.pid,"SIGKILL")}catch(n){if(this.isMissingProcessError(n))return;throw new t(`Failed to force-stop verified daemon process ${o.pid}: ${this.host.describeError(n)}`)}if(!(await this.host.waitForStop(o.pid,ik,o)).stopped)throw new t(`Verified daemon process ${o.pid} did not exit after SIGKILL`)}async verifyDaemonGenerationBeforeSignal(o,n,a="Daemon recovery"){if(!this.host.isProcessRunning(o.pid))return!1;if(o.startedAt===void 0&&o.processGenerationToken===void 0)throw new t(`${a} could not verify the recorded daemon process generation before signalling it.`);let s=this.host.findLiveDaemonProcessRecords(this.host.remainingRecoveryTime(n));this.host.remainingRecoveryTime(n);let c=s.find((u)=>u.pid===o.pid);if(this.assertObservedDaemonGeneration(o,c,a),c&&this.host.hasNamespaceRecordOrMarker(c))return this.host.isProcessRunning(o.pid);if(!c&&this.isRecycledPid(o))return e.info(`Recorded daemon PID ${o.pid} is now held by a different process generation; treating the recorded daemon as exited`),!1;let d=await this.host.probeNamespaceOwner();if(this.host.remainingRecoveryTime(n),!this.host.isProcessRunning(o.pid))return!1;let m=this.host.findLiveDaemonProcessRecords(this.host.remainingRecoveryTime(n)).find((u)=>u.pid===o.pid);if(this.host.remainingRecoveryTime(n),this.assertObservedDaemonGeneration(o,m,a),this.matchesSocketOwnerBeforeSignal(d,o,m))return this.host.isProcessRunning(o.pid);throw new t(`${a} could not verify the live PID's generation and ownership of this socket namespace; refusing to signal it.`)}assertObservedDaemonGeneration(o,n,a){if(n&&!this.host.matchesObservedDaemonGeneration(o,n))throw new t(`${a} found that the verified daemon PID was reused before signalling it.`)}matchesSocketOwnerBeforeSignal(o,n,a){if(!o||o.pid!==n.pid)return!1;if(!a&&(o.reportedSocketPath!==this.host.socketPath||o.reportedPidFilePath!==this.host.pidFilePath))return!1;if(a?.command.includes(ff))return!1;return this.host.matchesObservedDaemonGeneration(n,{pid:o.pid,ppid:0,command:"",startedAt:o.processStartedAt??o.startedAt,processGenerationToken:Dr(o)})}stopWaitTimeout(o,n){let a=this.host.remainingRecoveryTime(n);return a===void 0?o:Math.min(o,a)}isMissingProcessError(o){return o instanceof Error&&o.message.includes("ESRCH")}async waitForStop(o,n,a){let s=this.host.timer.now()+n,c=100,d=(u)=>{if(a===void 0)return!1;let p=this.host.identityRecoveryIO.readRecord();if(p===null)return!1;let D={pid:p.pid,ppid:0,command:"",startedAt:p.processStartedAt??p.startedAt,processGenerationToken:Dr(p)};return u.some((b)=>this.host.isConfirmedDifferentDaemonGeneration(a,b)&&this.host.matchesObservedDaemonGeneration(D,b))},m=()=>{if(!this.host.isProcessRunning(o))return{stopped:!0,replacedByOtherGeneration:!1};if(a===void 0)return;let u=this.host.remainingTime(s);if(u<=0)return;try{let p=this.host.findLiveDaemonProcessRecords(u);if(d(p))return{stopped:!0,replacedByOtherGeneration:!0}}catch(p){e.debug(`[DaemonManager] replacement scan failed during stop; treating this poll as inconclusive: ${r(p)}`)}return};while(this.host.remainingTime(s)>0){let u=m();if(u!==void 0)return u;await this.host.timer.sleep(100)}return m()??{stopped:!1,replacedByOtherGeneration:!1}}isProcessRunning(o){return this.host.processLivenessChecker.isProcessRunning(o)}isRecycledPid(o){let n=this.host.processLivenessChecker.readProcessGenerationToken;return n!==void 0&&cR(o.pid,o,(a)=>n.call(this.host.processLivenessChecker,a),this.host.pidFilePath)}isRecordedDaemonRunning(o){return this.host.isProcessRunning(o.pid)&&!this.isRecycledPid(o)}getPid(){if(!_e(this.host.pidFilePath))return null;try{let o=Pt("fs").readFileSync(this.host.pidFilePath,"utf-8");return JSON.parse(o).pid}catch(o){return e.debug(`src/daemon/manager.ts pidfile parse failed: ${o}`,o),null}}}var Xt=2000,Qt=50;var re=g({running:ne(!0),pid:T().int().positive(),startedAt:T().positive(),processStartedAt:T().positive().optional(),processGenerationToken:y().min(1).optional(),processGenerationTokenUtc:y().min(1).optional(),version:y().min(1),buildId:y().min(1),entryScript:y().min(1),socketPath:y().min(1),reportedPidFilePath:y().min(1),reportedSocketPath:y().min(1),reportedSockets:Dt(y(),y().min(1))}),x=g({accepted:te(),reason:y().optional()}),Zt=re.omit({running:!0,reportedPidFilePath:!0,reportedSocketPath:!0,reportedSockets:!0}).extend({port:T().int().positive(),dbPath:y().min(1),daemonSessionId:y().min(1),launchLogPath:y().nullable(),options:A_,sockets:Dt(y(),y().min(1))});function G(o,n){let a=Zt.safeParse(o);if(!a.success)return!1;let{sockets:s,socketPath:c}=a.data;return s.control===c&&Object.keys(s).length===Object.keys(n).length&&Object.entries(n).every(([d,m])=>s[d]===m)}async function kZ(o,n,a,s){if(!o)return!1;let c=a.readRecord();if(G(c,s)&&c.pid===n.pid&&c.startedAt===n.startedAt&&Dr(c)===n.processGenerationToken)return!0;if(c&&c.pid!==n.pid&&a.isProcessRunning(c.pid))return!1;return await a.writeRecord(),!0}class oe{host;recoveryOwner;identityRecoveryInFlight;constructor(o){this.host=o}async status(o=!0){if(!o)return this.host.recordedStatus();if(this.identityRecoveryInFlight)return this.identityRecoveryInFlight;let n=this.host.recordedStatus();if(n.running||!this.host.identityRecoveryIO.socketExists())return n;this.identityRecoveryInFlight=this.host.recoverSocketIdentity();try{return await this.identityRecoveryInFlight}finally{this.identityRecoveryInFlight=void 0}}recordedStatus(){let o=this.host.identityRecoveryIO.readRecord();return o&&o.socketPath===this.host.socketPath&&this.host.isRecordedDaemonRunning(o)?{...o,running:!0}:{running:!1}}lifecycleStatus(){return this.recoveryOwner?Promise.resolve(this.host.recordedStatus()):this.host.status()}async authenticateSocketOwner(){try{let o=await this.host.identityRecoveryIO.probe();if(!this.host.isRecoveryOwner(o))throw new t("Socket owner did not provide a live, matching provider identity");return o}catch(o){if(/ECONNREFUSED|ENOENT|Failed to connect to daemon/.test(r(o)))return e.debug("No daemon listening on the recovery socket",o),{running:!1};return e.warn("Daemon socket owner could not be authenticated",o),{running:!1,recovery:{state:"unauthenticated",reason:r(o)}}}}isRecoveryOwner(o){return re.safeParse(o).success&&o.reportedPidFilePath===this.host.pidFilePath&&o.reportedSocketPath===this.host.socketPath&&this.host.isProcessRunning(o.pid)}async recoverSocketIdentity(){this.host.markStartupLockRecovering();let o=await this.host.authenticateSocketOwner();if(!o.running)return o;let n=await this.requestIdentityRepublish(o);if(n.accepted)return await this.tryVerifiedRepair(o)??{running:!1,recovery:{state:"failed",reason:"Republish accepted without authoritative metadata"}};return{running:!1,recovery:{state:"deferred",reason:n.reason,replacementOwner:o}}}async replaceRecoveryOwner(o){this.recoveryOwner=o;try{this.host.markStartupLockRecovering();let n=await this.host.restart({},o);return await this.waitForRecoverySuccessor(o,n==="joined"?"joined":"replaced")}catch(n){return e.warn("Explicit daemon identity replacement did not complete",n),{running:!1,recovery:{state:n instanceof Or?"deferred":"failed",reason:r(n)}}}finally{this.recoveryOwner=void 0}}async waitForRecoverySuccessor(o,n){let a=this.host.timer.now()+5000;while(this.host.timer.now()<a){let s=await this.host.authenticateSocketOwner();if(s.running&&(n==="joined"||!this.host.isSameDaemonGeneration(s,o))&&this.host.hasPublishedRecoveryIdentity(s))return this.verifiedRecoveryStatus(n,s);await this.host.timer.sleep(100)}return{running:!1,recovery:{state:"failed",reason:"Successor did not publish complete identity within 5000ms"}}}async startIdentityRecovery(o){let n=o.recovery?.replacementOwner,a=n?await this.host.replaceRecoveryOwner(n):o;if(!a.running){let s=a.recovery?.reason??"Identity recovery could not be verified";if(a.recovery?.state==="deferred")throw new Or(s);throw new t(s)}return a.recovery?.state==="joined"?"joined":"replaced"}async requestIdentityRepublish(o){let n=this.host.createClient({clientIdentity:null});try{let a=await n.callDaemonMethod(rq,{...o});return x.parse(a)}catch(a){return e.warn("In-place daemon identity publication unavailable",a),{accepted:!1,reason:"republish_unavailable"}}finally{await n.close()}}hasPublishedRecoveryIdentity(o){let n=this.host.identityRecoveryIO.readRecord();return G(n,o.reportedSockets??{})&&this.host.isProcessRunning(n.pid)&&n.socketPath===this.host.socketPath&&this.host.isSameDaemonGeneration({...n,running:!0},o)}async tryVerifiedRepair(o){try{return await this.verifiedRecoveryStatus("repaired",o)}catch(n){e.warn("Daemon acknowledged repair without authoritative metadata",n);return}}async verifiedRecoveryStatus(o,n){let a=this.host.identityRecoveryIO.readRecord(),s=n??await this.host.identityRecoveryIO.probe();if(!this.host.isRecoveryOwner(s)||!G(a,s.reportedSockets??{})||!this.host.isProcessRunning(a.pid)||!this.host.isSameDaemonGeneration({...a,running:!0},s)||n&&!this.host.isSameDaemonGeneration(s,n)||a.socketPath!==this.host.socketPath)throw new t("Daemon recovery did not publish complete authoritative metadata");return{...a,running:!0,recovery:{state:o}}}}var er=3000;class ae{host;constructor(o){this.host=o}async restart(o={},n){return Le(this.restartHost(),o,n)}async restartAdmitted(o,n){return Ae(this.restartHost(),o,n)}isSameDaemonGeneration(o,n){if(!o.running||!n.running||o.pid!==n.pid)return!1;return["startedAt","processStartedAt","processGenerationToken","processGenerationTokenUtc","version","buildId","entryScript"].every((s)=>n[s]===void 0||o[s]===n[s])}async restartAcceptanceSession(o){return Te(this.restartHost(),o)}restartHost(){let o=this.host;return{get takeoverDeferrals(){return o.takeoverDeferrals},now:()=>this.host.timer.now(),log:(n)=>f(n),sleep:(n)=>this.host.timer.sleep(n),acquireLock:()=>this.host.acquireLock(),releaseLock:()=>this.host.releaseLock(),createClient:(n)=>this.host.createClient(n),lifecycleStatus:()=>this.host.lifecycleStatus(),recordedStatus:()=>this.host.recordedStatus(),probeRecoveryOwner:()=>this.host.identityRecoveryIO.probe(),isRecoveryOwnerReference:(n)=>n===this.host.recoveryOwner,isRecoveryOwner:(n)=>this.host.isRecoveryOwner(n),hasPublishedRecoveryIdentity:(n)=>this.host.hasPublishedRecoveryIdentity(n),isSameDaemonGeneration:(n,a)=>this.host.isSameDaemonGeneration(n,a),isConfirmedDifferentDaemonGeneration:(n,a)=>this.host.isConfirmedDifferentDaemonGeneration(n,a),daemonProcessRecordFromStatus:(n)=>this.host.daemonProcessRecordFromStatus(n),isProcessRunning:(n)=>this.host.isProcessRunning(n),signalProcess:(n,a)=>this.host.processSignaler.signal(n,a),stop:(n,a)=>this.host.stop(n,a),stopRunningDaemon:(n,a,s)=>this.host.stopRunningDaemon(n,a,s),stopNamespaceOrphansForExplicitRestart:(n)=>this.host.stopNamespaceOrphansForExplicitRestart(n),awaitRestartCleanup:(n)=>this.host.awaitRestartCleanup(n),waitForStop:(n,a,s)=>this.host.waitForStop(n,a,s),assertNoSurvivingDaemonBeforeRestart:(n)=>this.host.assertNoSurvivingDaemonBeforeRestart(n),cleanupAcceptanceRestartFiles:(n,a)=>this.host.cleanupAcceptanceRestartFiles(n,a),verifyDaemonGenerationBeforeSignal:(n,a,s)=>this.host.verifyDaemonGenerationBeforeSignal(n,a,s),prepareDaemonForConditionalRestart:(n)=>this.host.prepareDaemonForConditionalRestart(n),prepareIdentityRecoveryRestart:(n)=>this.host.prepareIdentityRecoveryRestart(n),admitMaintenanceRestart:(n,a)=>this.host.admitMaintenanceRestart(n,a),start:(n)=>this.host.start(n),startWithRunningOptions:(n)=>this.host.startWithRunningOptions(n),startUnlocked:(n,a,s)=>this.host.startUnlocked(n,a,s)}}async cleanupAcceptanceRestartFiles(o,n){if(n)return;await eb({pidFilePath:this.host.pidFilePath,socketPaths:this.host.cleanupSocketPaths(o.socketPath),expectedPid:o.pid})}async prepareDaemonForConditionalRestart(o){let n=this.host.createClient({clientIdentity:null});try{let a=await n.callDaemonMethod(nq,{pid:o.pid,startedAt:o.startedAt,..._d(Dr(o)),version:o.version,buildId:o.buildId,entryScript:o.entryScript},{timeoutMs:er});if(!a||typeof a!=="object")throw new Or("the daemon returned no safe-restart admission result");let s=a;if(s.accepted===!0)return{accepted:!0};if(s.accepted===!1&&(s.reason==="generation_changed"||s.reason==="restart_pending"||s.reason==="active_operations"||s.reason==="shutdown_unavailable"))return{accepted:!1,reason:s.reason};throw new Or("the daemon returned an unrecognized safe-restart admission result")}catch(a){if(a instanceof Or)throw a;throw new Or(`safe-restart admission is unavailable for daemon pid ${o.pid} (version ${o.version??"unknown"}; daemons before 0.0.74 predate it): ${r(a)}`)}finally{await n.close()}}async prepareIdentityRecoveryRestart(o){if(!o.dbPath||!o.options)throw new Or("incumbent database path or startup options unavailable");let n=this.host.createClient({clientIdentity:null}),a;try{let s=await n.callDaemonMethod(iq,{...o}),c=x.passthrough().parse(s);if(!c.accepted||typeof c.maintenanceToken!=="string")throw new Or(c.reason??"maintenance admission unavailable",c.reason);a=c.maintenanceToken;let d=await this.host.admitMaintenanceRestart(o,a);if(!d.accepted)throw new Or(d.reason??"maintenance admission refused",d.reason);return{accepted:!0}}finally{if(a)try{await n.callDaemonMethod(oq,{...o,maintenanceToken:a})}catch(s){e.debug("Maintenance release after identity recovery unavailable",s)}await n.close()}}async admitMaintenanceRestart(o,n){let a=this.host.createClient({clientIdentity:null});try{await a.connect();let s=await a.callDaemonMethod(sq,{pid:o.pid,startedAt:o.startedAt,..._d(Dr(o)),version:o.version,buildId:o.buildId,entryScript:o.entryScript,maintenanceToken:n});if(!s||typeof s!=="object")return{accepted:!1,reason:"maintenance_token_invalid"};let c=s;if(c.accepted===!0)return{accepted:!0};if(c.accepted===!1&&rr(c.reason))return{accepted:!1,reason:c.reason};return{accepted:!1,reason:"maintenance_token_invalid"}}catch(s){throw new Or(`maintenance admission is unavailable: ${r(s)}`)}finally{await a.close()}}}var tr=new Set(["active_operations","active_sessions","generation_changed","maintenance_token_invalid","maintenance_token_consumed","restart_pending","shutdown_unavailable","sessions_unavailable"]);function rr(o){return typeof o==="string"&&tr.has(o)}class op{get recoveryOwner(){return this.collaborators.daemonIdentityRecovery.recoveryOwner}identityRecoveryIO;clientFactory;stateProvider;timer;lockFilePath;pidFilePath;socketPath;processFinder;processLivenessChecker;processSignaler;retryExecutor;portAvailabilityChecker;extractionCleaner;launcher;fallbackLauncher;peerSocketReachability;daemonProtocolHealthProbe;launchCommandResolver;get heldLockLogPath(){return this.collaborators.daemonStartupLock.heldLockLogPath}seams={portFreeProbe:dr,exitRecordFileSystem:IA,launchLogFileSystem:{openSync:ar,closeSync:ir},launchWorkingDirectory:OU,currentBuildId:()=>Vo().buildId,nextLaunchNonce:()=>B.next(),probeLaunchCheckoutVersion:nM};startupLockOwnerToken;platform;lockOwnerGenerationProbe;constructor(o={}){let n=mr(o);this.lockOwnerGenerationProbe=n.lockOwnerGenerationProbe,this.identityRecoveryIO=n.identityRecoveryIO??{socketExists:()=>this.platform!=="win32"&&nr(this.socketPath),readRecord:()=>_o(this.pidFilePath),probe:()=>this.platform==="win32"?Promise.reject(Error("Failed to connect to daemon: socket-owner probing is unsupported on win32")):new Da(this.socketPath,1000,this.timer).getDaemonStatus(1000)},this.platform=n.platform,this.portAvailabilityChecker=n.portAvailabilityChecker,this.retryExecutor=n.retryExecutor,this.startupLockOwnerToken=n.idGenerator.next(),this.seams.nextLaunchNonce=()=>n.idGenerator.next(),this.peerSocketReachability=n.peerSocketReachability??new ER({timer:n.timer}),this.stateProvider=n.stateProvider,this.timer=n.timer,this.lockFilePath=Se(n.lockFilePath),this.pidFilePath=Se(n.pidFilePath),this.socketPath=Se(n.socketPath),this.processFinder=n.processFinder,this.processLivenessChecker=cr(n.processFinder)?n.processFinder:$D(),this.processSignaler=n.processSignaler,this.extractionCleaner=n.extractionCleaner,this.launchCommandResolver=n.launchCommandResolver,this.launcher=n.launcher??new aj({spawn:n.processSpawner?.spawn.bind(n.processSpawner),timer:n.timer}),this.fallbackLauncher=new aj({entryScript:null,spawn:n.processSpawner?.spawn.bind(n.processSpawner),timer:n.timer}),this.clientFactory=n.clientFactory??((a)=>new Da(this.socketPath,void 0,n.timer,{recoveryOptions:{},clientIdentity:a?.clientIdentity})),this.daemonProtocolHealthProbe=n.daemonProtocolHealthProbe??(async()=>{try{return await new Da(this.socketPath,void 0,this.timer).getDaemonStatus(),!0}catch(a){return e.debug(`Daemon control-state protocol probe failed: ${r(a)}`),!1}})}acquireLock(){return this.collaborators.daemonStartupLock.acquireLock()}releaseLock(){return this.collaborators.daemonStartupLock.releaseLock()}createClient(o){return this.clientFactory(o)}getDaemonState(){return this.stateProvider()}cleanupSocketPaths(o){return this.collaborators.daemonProcessDiscovery.cleanupSocketPaths(o)}findAllDaemonProcesses(o){return this.collaborators.daemonProcessDiscovery.findAllDaemonProcesses(o)}findOtherDaemonProcesses(o){return this.collaborators.daemonProcessDiscovery.findOtherDaemonProcesses(o)}findLiveDaemonProcesses(o){return this.collaborators.daemonProcessDiscovery.findLiveDaemonProcesses(o)}findLiveDaemonProcessRecords(o){return this.collaborators.daemonProcessDiscovery.findLiveDaemonProcessRecords(o)}hasNamespaceRecordOrMarker(o){return this.collaborators.daemonProcessDiscovery.hasNamespaceRecordOrMarker(o)}probeNamespaceOwner(){return this.collaborators.daemonProcessDiscovery.probeNamespaceOwner()}findNamespaceDaemonProcessRecords(o){return this.collaborators.daemonProcessDiscovery.findNamespaceDaemonProcessRecords(o)}findLiveDaemonProcessesForStart(o,n){return this.collaborators.daemonProcessDiscovery.findLiveDaemonProcessesForStart(o,n)}start(o={}){return this.collaborators.daemonStart.start(o)}startWithRunningOptions(o){return this.collaborators.daemonStart.startWithRunningOptions(o)}startByAwaitingLockHolder(o,n,a){return this.collaborators.daemonStartupLock.startByAwaitingLockHolder(o,n,a)}readSettledStartupLockHolder(o,n){return this.collaborators.daemonStartupLock.readSettledStartupLockHolder(o,n)}inheritExitSettings(o){return this.collaborators.daemonStart.inheritExitSettings(o)}startUnlocked(o,n,a=!0){return this.collaborators.daemonStart.startUnlocked(o,n,a)}launchWithExtractionRetry(o,n,a,s){return this.collaborators.daemonLaunch.launchWithExtractionRetry(o,n,a,s)}daemonLaunchEnvironment(o){return this.collaborators.daemonLaunch.daemonLaunchEnvironment(o)}withDaemonOptions(o,n){return this.collaborators.daemonLaunch.withDaemonOptions(o,n)}resolveLaunchCommand(){return this.collaborators.daemonLaunch.resolveLaunchCommand()}createLockHolderStartupFailure(o){return this.collaborators.daemonLaunch.createLockHolderStartupFailure(o)}readStartupLockHolder(){return this.collaborators.daemonStartupLock.readStartupLockHolder()}isStartupLockHeldByLiveProcess(){return this.collaborators.daemonStartupLock.isStartupLockHeldByLiveProcess()}waitForLockHolderReadiness(o){return this.collaborators.daemonStartupLock.waitForLockHolderReadiness(o)}markStartupLockRecovering(){return this.collaborators.daemonStartupLock.markStartupLockRecovering()}getLockHolderStartupLogPath(){return this.collaborators.daemonStartupLock.getLockHolderStartupLogPath()}daemonLaunchLogPath(){return this.collaborators.daemonLaunch.daemonLaunchLogPath()}createDaemonExitFailure(o,n,a){return this.collaborators.daemonLaunch.createDaemonExitFailure(o,n,a)}describeError(o){return this.collaborators.daemonLaunch.describeError(o)}stop(o=oo,n){return this.collaborators.daemonShutdown.stop(o,n)}recoverControlState(o={},n=this.daemonProtocolHealthProbe,a,s){return this.collaborators.daemonControlRecovery.recoverControlState(o,n,a,s)}matchesRecordedDaemonGeneration(o,n){return this.collaborators.daemonControlRecovery.matchesRecordedDaemonGeneration(o,n)}matchesObservedDaemonGeneration(o,n){return this.collaborators.daemonControlRecovery.matchesObservedDaemonGeneration(o,n)}isConfirmedDifferentDaemonGeneration(o,n){return this.collaborators.daemonControlRecovery.isConfirmedDifferentDaemonGeneration(o,n)}throwIfRecoveryCancelled(o){return this.collaborators.daemonControlRecovery.throwIfRecoveryCancelled(o)}remainingRecoveryTime(o){return this.collaborators.daemonControlRecovery.remainingRecoveryTime(o)}recoveryOptions(o,n){return this.collaborators.daemonControlRecovery.recoveryOptions(o,n)}stopRunningDaemon(o,n=oo,a=!0){return this.collaborators.daemonShutdown.stopRunningDaemon(o,n,a)}daemonProcessRecordFromStatus(o){return this.collaborators.daemonShutdown.daemonProcessRecordFromStatus(o)}removeConfirmedDeadPidFile(){return this.collaborators.daemonShutdown.removeConfirmedDeadPidFile()}status(o=!0){return this.collaborators.daemonIdentityRecovery.status(o)}recordedStatus(){return this.collaborators.daemonIdentityRecovery.recordedStatus()}lifecycleStatus(){return this.collaborators.daemonIdentityRecovery.lifecycleStatus()}authenticateSocketOwner(){return this.collaborators.daemonIdentityRecovery.authenticateSocketOwner()}isRecoveryOwner(o){return this.collaborators.daemonIdentityRecovery.isRecoveryOwner(o)}recoverSocketIdentity(){return this.collaborators.daemonIdentityRecovery.recoverSocketIdentity()}replaceRecoveryOwner(o){return this.collaborators.daemonIdentityRecovery.replaceRecoveryOwner(o)}startIdentityRecovery(o){return this.collaborators.daemonIdentityRecovery.startIdentityRecovery(o)}hasPublishedRecoveryIdentity(o){return this.collaborators.daemonIdentityRecovery.hasPublishedRecoveryIdentity(o)}restart(o={},n){return this.collaborators.daemonRestartCoordinator.restart(o,n)}restartAdmitted(o,n){return this.collaborators.daemonRestartCoordinator.restartAdmitted(o,n)}isSameDaemonGeneration(o,n){return this.collaborators.daemonRestartCoordinator.isSameDaemonGeneration(o,n)}restartAcceptanceSession(o){return this.collaborators.daemonRestartCoordinator.restartAcceptanceSession(o)}cleanupAcceptanceRestartFiles(o,n){return this.collaborators.daemonRestartCoordinator.cleanupAcceptanceRestartFiles(o,n)}prepareDaemonForConditionalRestart(o){return this.collaborators.daemonRestartCoordinator.prepareDaemonForConditionalRestart(o)}prepareIdentityRecoveryRestart(o){return this.collaborators.daemonRestartCoordinator.prepareIdentityRecoveryRestart(o)}admitMaintenanceRestart(o,n){return this.collaborators.daemonRestartCoordinator.admitMaintenanceRestart(o,n)}assertNoSurvivingDaemonBeforeRestart(o,n){return this.collaborators.daemonShutdown.assertNoSurvivingDaemonBeforeRestart(o,n)}stopNamespaceOrphansForExplicitRestart(o){return this.collaborators.daemonShutdown.stopNamespaceOrphansForExplicitRestart(o)}awaitRestartCleanup(o){return this.collaborators.daemonShutdown.awaitRestartCleanup(o)}stopUnrecordedDaemonProcess(o,n,a){return this.collaborators.daemonShutdown.stopUnrecordedDaemonProcess(o,n,a)}verifyDaemonGenerationBeforeSignal(o,n,a="Daemon recovery"){return this.collaborators.daemonShutdown.verifyDaemonGenerationBeforeSignal(o,n,a)}waitForReady(o,{signal:n,shouldContinueWaiting:a=()=>!0,maxProbeDurationMs:s,launchedProcess:c}={}){return this.collaborators.daemonReadiness.waitForReady(o,{signal:n,shouldContinueWaiting:a,maxProbeDurationMs:s,launchedProcess:c})}tryJoinPeerDaemonAfterSpawnExit(o){return this.collaborators.daemonReadiness.tryJoinPeerDaemonAfterSpawnExit(o)}waitForExistingDaemon(o){return this.collaborators.daemonReadiness.waitForExistingDaemon(o)}sleepUnlessAborted(o,n){return this.collaborators.daemonReadiness.sleepUnlessAborted(o,n)}remainingTime(o){return this.collaborators.daemonReadiness.remainingTime(o)}socketPathObservable(){return this.collaborators.daemonReadiness.socketPathObservable()}getInternalsForTesting(){return{seams:this.seams,identityRecoveryIO:this.identityRecoveryIO,inheritExitSettings:(o)=>this.inheritExitSettings(o),recoveryOptions:(o,n)=>this.recoveryOptions(o,n),tryJoinPeerDaemonAfterSpawnExit:(o)=>this.tryJoinPeerDaemonAfterSpawnExit(o),isIsolatedSocketNamespace:()=>this.isIsolatedSocketNamespace()}}isIsolatedSocketNamespace(){return this.collaborators.daemonReadiness.isIsolatedSocketNamespace()}verifyDaemonConnection(o,n){return this.collaborators.daemonReadiness.verifyDaemonConnection(o,n)}isLaunchedProcessReady(o,n,a,s){return this.collaborators.daemonReadiness.isLaunchedProcessReady(o,n,a,s)}waitForStop(o,n,a){return this.collaborators.daemonShutdown.waitForStop(o,n,a)}isProcessRunning(o){return this.collaborators.daemonShutdown.isProcessRunning(o)}get testHooks(){return{identityRecoveryIO:this.identityRecoveryIO,launcher:this.launcher,isProcessRunning:(o)=>this.isProcessRunning(o),readStartupLockHolder:()=>this.readStartupLockHolder(),readSettledStartupLockHolder:(o,n)=>this.readSettledStartupLockHolder(o,n),markStartupLockRecovering:()=>this.markStartupLockRecovering(),recoverSocketIdentity:()=>this.recoverSocketIdentity(),replaceRecoveryOwner:(o)=>this.replaceRecoveryOwner(o),startUnlocked:(o)=>this.startUnlocked(o),daemonLaunchEnvironment:(o)=>this.daemonLaunchEnvironment(o)}}isRecordedDaemonRunning(o){return this.collaborators.daemonShutdown.isRecordedDaemonRunning(o)}getPid(){return this.collaborators.daemonShutdown.getPid()}collaborators=this.createCollaborators();createCollaborators(){let o=this.collaboratorHost();return{daemonProcessDiscovery:new W(o),daemonStartupLock:new q(o),daemonStart:new Y(o),daemonLaunch:new V(o),daemonControlRecovery:new Z(o),daemonShutdown:new ee(o),daemonIdentityRecovery:new oe(o),daemonRestartCoordinator:new ae(o),daemonReadiness:new K(o)}}collaboratorHost(){let o=this,n;return{...this.collaboratorOperations(),get takeoverDeferrals(){return n??=new z(new aD(`${o.pidFilePath}.takeover-deferral.json`))},get pidFilePath(){return o.pidFilePath},get processFinder(){return o.processFinder},get socketPath(){return o.socketPath},get identityRecoveryIO(){return o.identityRecoveryIO},get retryExecutor(){return o.retryExecutor},get portAvailabilityChecker(){return o.portAvailabilityChecker},get lockFilePath(){return o.lockFilePath},get lockOwnerGenerationProbe(){return o.lockOwnerGenerationProbe},get startupLockOwnerToken(){return o.startupLockOwnerToken},get heldLockLogPath(){return o.heldLockLogPath},get timer(){return o.timer},get seams(){return o.seams},get launcher(){return o.launcher},get fallbackLauncher(){return o.fallbackLauncher},get extractionCleaner(){return o.extractionCleaner},get recoveryOwner(){return o.recoveryOwner},get launchCommandResolver(){return o.launchCommandResolver},get processSignaler(){return o.processSignaler},get processLivenessChecker(){return o.processLivenessChecker},get peerSocketReachability(){return o.peerSocketReachability},get platform(){return o.platform}}}collaboratorOperations(){return{findLiveDaemonProcessRecords:(...o)=>this.findLiveDaemonProcessRecords(...o),hasNamespaceRecordOrMarker:(...o)=>this.hasNamespaceRecordOrMarker(...o),findAllDaemonProcesses:(...o)=>this.findAllDaemonProcesses(...o),isProcessRunning:(...o)=>this.isProcessRunning(...o),recordedStatus:(...o)=>this.recordedStatus(...o),matchesRecordedDaemonGeneration:(...o)=>this.matchesRecordedDaemonGeneration(...o),probeNamespaceOwner:(...o)=>this.probeNamespaceOwner(...o),remainingTime:(...o)=>this.remainingTime(...o),findNamespaceDaemonProcessRecords:(...o)=>this.findNamespaceDaemonProcessRecords(...o),daemonLaunchLogPath:(...o)=>this.daemonLaunchLogPath(...o),readStartupLockHolder:(...o)=>this.readStartupLockHolder(...o),throwIfRecoveryCancelled:(...o)=>this.throwIfRecoveryCancelled(...o),getLockHolderStartupLogPath:(...o)=>this.getLockHolderStartupLogPath(...o),acquireLock:(...o)=>this.acquireLock(...o),startUnlocked:(...o)=>this.startUnlocked(...o),releaseLock:(...o)=>this.releaseLock(...o),createLockHolderStartupFailure:(...o)=>this.createLockHolderStartupFailure(...o),readSettledStartupLockHolder:(...o)=>this.readSettledStartupLockHolder(...o),waitForReady:(...o)=>this.waitForReady(...o),sleepUnlessAborted:(...o)=>this.sleepUnlessAborted(...o),socketPathObservable:(...o)=>this.socketPathObservable(...o),verifyDaemonConnection:(...o)=>this.verifyDaemonConnection(...o),authenticateSocketOwner:(...o)=>this.authenticateSocketOwner(...o),hasPublishedRecoveryIdentity:(...o)=>this.hasPublishedRecoveryIdentity(...o),describeError:(...o)=>this.describeError(...o),startByAwaitingLockHolder:(...o)=>this.startByAwaitingLockHolder(...o),start:(...o)=>this.start(...o),lifecycleStatus:(...o)=>this.lifecycleStatus(...o),verifyDaemonGenerationBeforeSignal:(...o)=>this.verifyDaemonGenerationBeforeSignal(...o),daemonProcessRecordFromStatus:(...o)=>this.daemonProcessRecordFromStatus(...o),waitForExistingDaemon:(...o)=>this.waitForExistingDaemon(...o),startIdentityRecovery:(...o)=>this.startIdentityRecovery(...o),prepareDaemonForConditionalRestart:(...o)=>this.prepareDaemonForConditionalRestart(...o),stopRunningDaemon:(...o)=>this.stopRunningDaemon(...o),assertNoSurvivingDaemonBeforeRestart:(...o)=>this.assertNoSurvivingDaemonBeforeRestart(...o),findLiveDaemonProcessesForStart:(...o)=>this.findLiveDaemonProcessesForStart(...o),inheritExitSettings:(...o)=>this.inheritExitSettings(...o),withDaemonOptions:(...o)=>this.withDaemonOptions(...o),resolveLaunchCommand:(...o)=>this.resolveLaunchCommand(...o),daemonLaunchEnvironment:(...o)=>this.daemonLaunchEnvironment(...o),launchWithExtractionRetry:(...o)=>this.launchWithExtractionRetry(...o),tryJoinPeerDaemonAfterSpawnExit:(...o)=>this.tryJoinPeerDaemonAfterSpawnExit(...o),isLaunchedProcessReady:(...o)=>this.isLaunchedProcessReady(...o),createDaemonExitFailure:(...o)=>this.createDaemonExitFailure(...o),remainingRecoveryTime:(...o)=>this.remainingRecoveryTime(...o),recoveryOptions:(...o)=>this.recoveryOptions(...o),stopUnrecordedDaemonProcess:(...o)=>this.stopUnrecordedDaemonProcess(...o),status:(...o)=>this.status(...o),removeConfirmedDeadPidFile:(...o)=>this.removeConfirmedDeadPidFile(...o),waitForStop:(...o)=>this.waitForStop(...o),cleanupSocketPaths:(...o)=>this.cleanupSocketPaths(...o),isRecordedDaemonRunning:(...o)=>this.isRecordedDaemonRunning(...o),awaitRestartCleanup:(...o)=>this.awaitRestartCleanup(...o),matchesObservedDaemonGeneration:(...o)=>this.matchesObservedDaemonGeneration(...o),isConfirmedDifferentDaemonGeneration:(...o)=>this.isConfirmedDifferentDaemonGeneration(...o),recoverSocketIdentity:(...o)=>this.recoverSocketIdentity(...o),isRecoveryOwner:(...o)=>this.isRecoveryOwner(...o),markStartupLockRecovering:(...o)=>this.markStartupLockRecovering(...o),restart:(...o)=>this.restart(...o),isSameDaemonGeneration:(...o)=>this.isSameDaemonGeneration(...o),replaceRecoveryOwner:(...o)=>this.replaceRecoveryOwner(...o),createClient:(...o)=>this.createClient(...o),stop:(...o)=>this.stop(...o),stopNamespaceOrphansForExplicitRestart:(...o)=>this.stopNamespaceOrphansForExplicitRestart(...o),cleanupAcceptanceRestartFiles:(...o)=>this.cleanupAcceptanceRestartFiles(...o),prepareIdentityRecoveryRestart:(...o)=>this.prepareIdentityRecoveryRestart(...o),admitMaintenanceRestart:(...o)=>this.admitMaintenanceRestart(...o),startWithRunningOptions:(...o)=>this.startWithRunningOptions(...o),isIsolatedSocketNamespace:(...o)=>this.isIsolatedSocketNamespace(...o)}}}var sr={signal(o,n){process.kill(o,n)}};function cr(o){return typeof o?.isProcessRunning==="function"}function dr(o){return new Promise((n)=>{let a=or();a.once("error",()=>n(!1)),a.listen(o,()=>a.close(()=>n(!0)))})}async function wce(o,n,a={}){return P4(o,n,a,op)}function mr(o){let n=lr(o),{extractionCleaner:a=le,processSignaler:s=sr,idGenerator:c=B,platform:d=process.platform,portAvailabilityChecker:m=new l$,retryExecutor:u=new kn(n.timer),lockOwnerGenerationProbe:p=kt}=o;return{...o,...n,extractionCleaner:a,processSignaler:s,idGenerator:c,platform:d,portAvailabilityChecker:m,retryExecutor:u,lockOwnerGenerationProbe:p}}function lr(o){let{stateProvider:n=()=>yB(w),timer:a=i,lockFilePath:s=vz,pidFilePath:c=Sr,socketPath:d=Bt,processFinder:m=$D()}=o;return{stateProvider:n,timer:a,lockFilePath:s,pidFilePath:c,socketPath:d,processFinder:m}}export{rq,nq,iq,oq,sq,aq,cq,dq,Or,qI,IA,AZ,l4,os,u4,p4,TZ,lq,m4,kZ,op,wce};
8
+
9
+ //# debugId=3127BDA02810C17C64756E2164756E21