@kaeawc/auto-mobile 0.0.93 → 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 (228) hide show
  1. package/dist/build-info.json +12 -12
  2. package/dist/src/ble-peripheral.py +153 -0
  3. package/dist/src/{chunk-r6z1eztj.js → chunk-026y62r9.js} +11 -11
  4. package/dist/src/chunk-0jyfg947.js +4 -0
  5. package/dist/src/{chunk-8g1922rp.js → chunk-0zfpp1wh.js} +4 -4
  6. package/dist/src/{chunk-qf6nynk6.js → chunk-13qxf7ym.js} +5 -5
  7. package/dist/src/chunk-1scenrk7.js +4 -0
  8. package/dist/src/chunk-1vb5ph1k.js +4 -0
  9. package/dist/src/{chunk-710rxz9y.js → chunk-20g565q7.js} +3 -3
  10. package/dist/src/chunk-21h6dhdm.js +5 -0
  11. package/dist/src/chunk-25mfpthk.js +78 -0
  12. package/dist/src/{chunk-rbpdk7m0.js → chunk-2b39zyxc.js} +3 -3
  13. package/dist/src/chunk-2gzd6wbd.js +4 -0
  14. package/dist/src/{chunk-xgan0qqp.js → chunk-3dntffy9.js} +1 -1
  15. package/dist/src/chunk-3gfczcsn.js +4 -0
  16. package/dist/src/{chunk-dgrbdpb7.js → chunk-3h5jz1vb.js} +6 -6
  17. package/dist/src/{chunk-t6c8akcm.js → chunk-41zcy6b3.js} +3 -3
  18. package/dist/src/chunk-47n9m2de.js +4 -0
  19. package/dist/src/chunk-4vxeq0vd.js +58 -0
  20. package/dist/src/chunk-59dx6qaf.js +4 -0
  21. package/dist/src/chunk-5sdf9y92.js +4 -0
  22. package/dist/src/{chunk-58wzr3mt.js → chunk-5wk1t46v.js} +3 -3
  23. package/dist/src/{chunk-vy3bwm1d.js → chunk-661c50hh.js} +5 -5
  24. package/dist/src/chunk-68n6bjjd.js +21 -0
  25. package/dist/src/{chunk-v6pya0dm.js → chunk-69pmjdf2.js} +3 -3
  26. package/dist/src/{chunk-e98dqnc9.js → chunk-6hrj3jt6.js} +20 -20
  27. package/dist/src/{chunk-wbh8spm5.js → chunk-6myr26wx.js} +8 -8
  28. package/dist/src/chunk-6n96k09n.js +4 -0
  29. package/dist/src/chunk-6vwrbkre.js +4 -0
  30. package/dist/src/chunk-6wk0yrab.js +4 -0
  31. package/dist/src/chunk-6yhm9een.js +4 -0
  32. package/dist/src/{chunk-mjrps0ac.js → chunk-7k7gjg2t.js} +5 -5
  33. package/dist/src/chunk-7n5fz68h.js +4 -0
  34. package/dist/src/chunk-8cvnpnbp.js +4 -0
  35. package/dist/src/chunk-8kzv7rk7.js +4 -0
  36. package/dist/src/chunk-8nj68t1v.js +167 -0
  37. package/dist/src/{chunk-g7tmjbkt.js → chunk-96r3bpg7.js} +3 -3
  38. package/dist/src/chunk-97x887te.js +4 -0
  39. package/dist/src/{chunk-8ph29g99.js → chunk-99a6tbvd.js} +1 -1
  40. package/dist/src/chunk-9p5d2994.js +5 -0
  41. package/dist/src/{chunk-aabchzxk.js → chunk-9q265er0.js} +4 -4
  42. package/dist/src/{chunk-jh6vhqzx.js → chunk-9xgnrv5w.js} +3 -3
  43. package/dist/src/chunk-9xgsmshb.js +5 -0
  44. package/dist/src/chunk-a02d1wgv.js +4 -0
  45. package/dist/src/{chunk-ndt1ccxm.js → chunk-a9ps00a1.js} +10 -10
  46. package/dist/src/{chunk-5d2hft6c.js → chunk-aewdveet.js} +3 -3
  47. package/dist/src/{chunk-ycaj2sgf.js → chunk-b3tdtq7r.js} +6 -6
  48. package/dist/src/chunk-bn7jx7a2.js +4 -0
  49. package/dist/src/{chunk-3y6eykz9.js → chunk-bnyw27ja.js} +2 -2
  50. package/dist/src/{chunk-rqc9ap3x.js → chunk-bpwsg76p.js} +2 -2
  51. package/dist/src/chunk-bvranw3g.js +4 -0
  52. package/dist/src/chunk-c25a84zb.js +4 -0
  53. package/dist/src/chunk-c27yv1dx.js +5 -0
  54. package/dist/src/chunk-c3ewxm4x.js +5 -0
  55. package/dist/src/{chunk-rvvy1bte.js → chunk-cb1ga9rd.js} +5 -5
  56. package/dist/src/chunk-cn7fwy7k.js +4 -0
  57. package/dist/src/chunk-cnvy4a64.js +4 -0
  58. package/dist/src/{chunk-7rz9898k.js → chunk-cqhw4yr6.js} +3 -3
  59. package/dist/src/{chunk-g04bwyj3.js → chunk-ctmfshjc.js} +2 -2
  60. package/dist/src/chunk-ctwmhz13.js +4 -0
  61. package/dist/src/{chunk-waqwcjyn.js → chunk-d3jx9bz5.js} +2 -2
  62. package/dist/src/{chunk-ayp07wbb.js → chunk-d6rb08ga.js} +1 -1
  63. package/dist/src/chunk-ddqhj4eg.js +5 -0
  64. package/dist/src/{chunk-r7bpkgff.js → chunk-ddrhs1c3.js} +2 -2
  65. package/dist/src/chunk-dnjnh9p6.js +4 -0
  66. package/dist/src/{chunk-wyrkw6hw.js → chunk-dw5rwgya.js} +3 -3
  67. package/dist/src/{chunk-3xkpk44w.js → chunk-e0870khr.js} +3 -3
  68. package/dist/src/chunk-ea3k10kj.js +4 -0
  69. package/dist/src/chunk-emv82m1w.js +7 -0
  70. package/dist/src/chunk-f3m6pdnx.js +4 -0
  71. package/dist/src/chunk-f84z32cb.js +4 -0
  72. package/dist/src/chunk-fpczgf0z.js +4 -0
  73. package/dist/src/{chunk-2tqzq5qh.js → chunk-g2js4c2v.js} +18 -18
  74. package/dist/src/chunk-g3af2qbk.js +5 -0
  75. package/dist/src/{chunk-3qwrzxh0.js → chunk-gadtna7s.js} +6 -6
  76. package/dist/src/{chunk-ybbtagbt.js → chunk-gcyx407v.js} +3 -3
  77. package/dist/src/{chunk-bfw6125s.js → chunk-gfpntwc1.js} +3 -3
  78. package/dist/src/chunk-gmnm5e3e.js +4 -0
  79. package/dist/src/chunk-gp6vb5gf.js +4 -0
  80. package/dist/src/chunk-gppgy7pa.js +4 -0
  81. package/dist/src/chunk-hegfz0ae.js +5 -0
  82. package/dist/src/chunk-hpzxdp1k.js +17 -0
  83. package/dist/src/{chunk-qcxzr2my.js → chunk-j69g8b50.js} +3 -3
  84. package/dist/src/chunk-jvstjnqm.js +19 -0
  85. package/dist/src/chunk-jzqrv78s.js +4 -0
  86. package/dist/src/chunk-k2948b8d.js +4 -0
  87. package/dist/src/chunk-k4ftd40d.js +4 -0
  88. package/dist/src/{chunk-bxmsax22.js → chunk-kd9vfaxh.js} +3 -3
  89. package/dist/src/{chunk-s3jc6cwp.js → chunk-kdczmgwk.js} +3 -3
  90. package/dist/src/{chunk-t6bfvfkg.js → chunk-ke3wn14v.js} +1 -1
  91. package/dist/src/chunk-kh5n7m6w.js +4 -0
  92. package/dist/src/{chunk-6wt9rgjf.js → chunk-khejfph4.js} +3 -3
  93. package/dist/src/chunk-kny2xemh.js +4 -0
  94. package/dist/src/chunk-knyzw9md.js +4 -0
  95. package/dist/src/chunk-mbzpt2hp.js +4 -0
  96. package/dist/src/chunk-mm8rcxad.js +4 -0
  97. package/dist/src/chunk-nc4516tx.js +4 -0
  98. package/dist/src/{chunk-6bznss4t.js → chunk-ntfrqrqn.js} +5 -5
  99. package/dist/src/chunk-nz5h2j52.js +4 -0
  100. package/dist/src/chunk-p22s97qy.js +4 -0
  101. package/dist/src/chunk-p9kt1sgr.js +6 -0
  102. package/dist/src/{chunk-yb97j25b.js → chunk-pf282r5g.js} +4 -4
  103. package/dist/src/chunk-pnd4mrxy.js +4 -0
  104. package/dist/src/chunk-pqqteyj6.js +4 -0
  105. package/dist/src/{chunk-6xmss8er.js → chunk-qj1tbnv2.js} +6 -6
  106. package/dist/src/chunk-qnh9egwr.js +4 -0
  107. package/dist/src/chunk-qy3khhf8.js +8 -0
  108. package/dist/src/{chunk-z637nqg8.js → chunk-r0vp315h.js} +6 -6
  109. package/dist/src/chunk-r4j43b9s.js +237 -0
  110. package/dist/src/{chunk-1p7xf5kb.js → chunk-r54cxxze.js} +3 -3
  111. package/dist/src/{chunk-yf7ympyz.js → chunk-r6pvhj33.js} +92 -92
  112. package/dist/src/chunk-rb7aa5gr.js +54 -0
  113. package/dist/src/chunk-rdj50kb4.js +4 -0
  114. package/dist/src/chunk-rnd4vcas.js +4 -0
  115. package/dist/src/{chunk-w5b2jwk3.js → chunk-s3y3zfcx.js} +8 -8
  116. package/dist/src/chunk-s4g43k75.js +5 -0
  117. package/dist/src/chunk-sfqe223f.js +311 -0
  118. package/dist/src/{chunk-284ptqa4.js → chunk-sqdrxjw5.js} +5 -5
  119. package/dist/src/{chunk-zgja5f3p.js → chunk-t54k47em.js} +4 -4
  120. package/dist/src/{chunk-3sy6ahhz.js → chunk-tek4pnvv.js} +10 -10
  121. package/dist/src/chunk-tn74y7af.js +4 -0
  122. package/dist/src/{chunk-thbh3jew.js → chunk-tvq0nzam.js} +3 -3
  123. package/dist/src/{chunk-0jrrsnc9.js → chunk-tx4f0h9c.js} +4 -4
  124. package/dist/src/chunk-vdqag3fj.js +5 -0
  125. package/dist/src/chunk-vz5zzs57.js +4 -0
  126. package/dist/src/chunk-w4s2vfpj.js +4 -0
  127. package/dist/src/{chunk-4hw3665t.js → chunk-w5yypt53.js} +11 -11
  128. package/dist/src/{chunk-8037tzzj.js → chunk-w68v64vh.js} +3 -3
  129. package/dist/src/chunk-whwj0pdk.js +5 -0
  130. package/dist/src/chunk-wnmqt1dc.js +4 -0
  131. package/dist/src/{chunk-cyy71ggq.js → chunk-wpe46vsa.js} +3 -3
  132. package/dist/src/{chunk-w3vs79ex.js → chunk-wxdjeb4k.js} +19 -19
  133. package/dist/src/chunk-xcqzwf9j.js +247 -0
  134. package/dist/src/chunk-xezekwwn.js +5 -0
  135. package/dist/src/chunk-xf19m15s.js +4 -0
  136. package/dist/src/chunk-xghbxha4.js +4 -0
  137. package/dist/src/{chunk-00167wan.js → chunk-xn9m3xc2.js} +5 -5
  138. package/dist/src/{chunk-26k317v5.js → chunk-yqfz4vts.js} +3 -3
  139. package/dist/src/chunk-z8tvs8nk.js +5 -0
  140. package/dist/src/chunk-zm2rehqb.js +5 -0
  141. package/dist/src/chunk-zs6dqm35.js +4 -0
  142. package/dist/src/daemon/processEntry.js +2 -2
  143. package/dist/src/index.js +4 -4
  144. package/dist/src/runtime/bunRuntimeGuard.js +2 -2
  145. package/dist/src/utils/workers/iosBundleExtractWorker.js +2 -2
  146. package/package.json +2 -2
  147. package/dist/src/chunk-0n6swkwg.js +0 -5
  148. package/dist/src/chunk-0qsy1qsx.js +0 -57
  149. package/dist/src/chunk-11m8wj8j.js +0 -237
  150. package/dist/src/chunk-23p5f095.js +0 -4
  151. package/dist/src/chunk-28re4xrg.js +0 -4
  152. package/dist/src/chunk-2f9rkmhx.js +0 -5
  153. package/dist/src/chunk-2fxdh48t.js +0 -4
  154. package/dist/src/chunk-2tbdrbt6.js +0 -4
  155. package/dist/src/chunk-32gvv9b4.js +0 -21
  156. package/dist/src/chunk-3f3t1x97.js +0 -8
  157. package/dist/src/chunk-3fspkbc7.js +0 -4
  158. package/dist/src/chunk-3vg455e6.js +0 -4
  159. package/dist/src/chunk-49bsqdx3.js +0 -4
  160. package/dist/src/chunk-5snsn9cf.js +0 -4
  161. package/dist/src/chunk-5tm9mn47.js +0 -54
  162. package/dist/src/chunk-5zc77a5t.js +0 -4
  163. package/dist/src/chunk-64j0majr.js +0 -19
  164. package/dist/src/chunk-65y8v4td.js +0 -17
  165. package/dist/src/chunk-6awz7vhq.js +0 -5
  166. package/dist/src/chunk-6ep7f5ge.js +0 -4
  167. package/dist/src/chunk-7cs2da62.js +0 -5
  168. package/dist/src/chunk-7g103b54.js +0 -4
  169. package/dist/src/chunk-7j5vj4pa.js +0 -4
  170. package/dist/src/chunk-7tw8x05v.js +0 -4
  171. package/dist/src/chunk-7zy586cb.js +0 -4
  172. package/dist/src/chunk-84nanf8s.js +0 -5
  173. package/dist/src/chunk-8gvwcv2p.js +0 -4
  174. package/dist/src/chunk-8thrmfat.js +0 -4
  175. package/dist/src/chunk-8zgzzs7k.js +0 -78
  176. package/dist/src/chunk-97b1zmaq.js +0 -4
  177. package/dist/src/chunk-9fth9ayh.js +0 -4
  178. package/dist/src/chunk-9j6anhjr.js +0 -4
  179. package/dist/src/chunk-bfjwqk8q.js +0 -4
  180. package/dist/src/chunk-bnhscm2n.js +0 -4
  181. package/dist/src/chunk-c1vs4g1n.js +0 -4
  182. package/dist/src/chunk-ct3e7yng.js +0 -4
  183. package/dist/src/chunk-ddzkz92z.js +0 -4
  184. package/dist/src/chunk-drdz8hee.js +0 -5
  185. package/dist/src/chunk-eersndy7.js +0 -5
  186. package/dist/src/chunk-eggq53ks.js +0 -4
  187. package/dist/src/chunk-f2dya7cs.js +0 -4
  188. package/dist/src/chunk-fbakd6cw.js +0 -4
  189. package/dist/src/chunk-fgb98zjj.js +0 -5
  190. package/dist/src/chunk-fmpad823.js +0 -5
  191. package/dist/src/chunk-g0xr8zw0.js +0 -4
  192. package/dist/src/chunk-g3rjs80x.js +0 -4
  193. package/dist/src/chunk-g78rtrfv.js +0 -4
  194. package/dist/src/chunk-gabgv3y5.js +0 -4
  195. package/dist/src/chunk-gmr45m8f.js +0 -4
  196. package/dist/src/chunk-gsyfebqj.js +0 -4
  197. package/dist/src/chunk-h5rpn9wr.js +0 -247
  198. package/dist/src/chunk-hb1x7v55.js +0 -4
  199. package/dist/src/chunk-hrfytkxh.js +0 -168
  200. package/dist/src/chunk-j4yjzbak.js +0 -4
  201. package/dist/src/chunk-jd6a5v6p.js +0 -5
  202. package/dist/src/chunk-kn5spq15.js +0 -4
  203. package/dist/src/chunk-m94qs0f0.js +0 -4
  204. package/dist/src/chunk-n03dmn5q.js +0 -5
  205. package/dist/src/chunk-n72qhwd9.js +0 -4
  206. package/dist/src/chunk-nr6y0n4y.js +0 -5
  207. package/dist/src/chunk-pcsen2vs.js +0 -4
  208. package/dist/src/chunk-ppfr0b8h.js +0 -4
  209. package/dist/src/chunk-q10bdnat.js +0 -4
  210. package/dist/src/chunk-q9xmq595.js +0 -4
  211. package/dist/src/chunk-qyqypn28.js +0 -5
  212. package/dist/src/chunk-r2epb56s.js +0 -4
  213. package/dist/src/chunk-r5bxavdx.js +0 -311
  214. package/dist/src/chunk-r8jf3d92.js +0 -4
  215. package/dist/src/chunk-rc0dbypm.js +0 -4
  216. package/dist/src/chunk-rhcty4ms.js +0 -4
  217. package/dist/src/chunk-rpvckv3p.js +0 -4
  218. package/dist/src/chunk-ry0mz41y.js +0 -4
  219. package/dist/src/chunk-sfv61xjb.js +0 -6
  220. package/dist/src/chunk-t7w8rctc.js +0 -4
  221. package/dist/src/chunk-v2wd4n3e.js +0 -5
  222. package/dist/src/chunk-w4zga19f.js +0 -4
  223. package/dist/src/chunk-w7hkv422.js +0 -5
  224. package/dist/src/chunk-xa73x2cx.js +0 -5
  225. package/dist/src/chunk-y2vs6jwg.js +0 -4
  226. package/dist/src/chunk-yattm52s.js +0 -4
  227. package/dist/src/chunk-yjawdzk8.js +0 -4
  228. package/dist/src/chunk-zs1sghs9.js +0 -4
@@ -1,9 +1,9 @@
1
1
  // @bun
2
- import{i,Ub,gU,_d,Se,gK,gae,vK,Wt,Ef,l,at,bJ,e}from"./chunk-z637nqg8.js";import{f}from"./chunk-58wzr3mt.js";import{O4,Vc,pQ}from"./chunk-hrfytkxh.js";import{mK,LO}from"./chunk-5d2hft6c.js";import{R,QL,Dr,hre,nd,iB,Lt,YW,br,JW,yre,rn,XW,io,HT,tD,vre,bre,dl,Ow,ez,wre,ri,ll,ul,Cre,Dre,Bv,Eo,Vw,Ore,wn,Vv,$s,dR,$z,Zm,DB,dY,RD,jB}from"./chunk-r5bxavdx.js";import{Ho,he,f_,nV,Ia}from"./chunk-64j0majr.js";import{B,wd,_r,Ya,Sa,Ht,Jg,ks,oP,Fi,ki,Db,AO}from"./chunk-yf7ympyz.js";import{y,T,ee,g,Ct,ne,A}from"./chunk-4hw3665t.js";import{jC}from"./chunk-0qsy1qsx.js";import{o4}from"./chunk-65y8v4td.js";import{Nc}from"./chunk-6wt9rgjf.js";import{r,t}from"./chunk-rbpdk7m0.js";import{wt}from"./chunk-qcxzr2my.js";var UH="ide/republishIdentity",HH="ide/prepareRestart",qH="ide/prepareMaintenance",VH="ide/completeMaintenance",WH="ide/restartAdmitted",zH="ide/restartAcceptanceSession",jH="ide/commitAcceptanceRestart",KH="ide/releaseAcceptanceRestart",ce=1000;class xr extends he{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 kI(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(!Nc(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 lA={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:f_});function H(o){return`${o}.exit-record.json`}function e7(o,n,a=lA){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=lA){try{n.rmSync(H(o),{force:!0})}catch(a){e.warn(`Failed to remove daemon exit record: ${r(a)}`,a)}}function fe(o,n=lA){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 De(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 z6{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===br)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:DB(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(Zm))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(Zm))?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:_r(a)});return n.filter((s)=>{let c=this.host.hasNamespaceRecordOrMarker(s)||!s.command.includes(Zm)&&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=Wt(bre),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(tD,p))).map((D)=>D.pid)},{maxAttempts:vre,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??nd,a=[n];if(nd!==n)a.push(nd);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(dY(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 Dt}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=[f.ENABLED_TOOLS.name,f.DISABLED_TOOLS.name,"AUTOMOBILE_TOOL_RESULTS_NO_STRUCTURED_CONTENT","AUTOMOBILE_ACTIONS_COMPACT_METADATA"];function ns(o){let n={...o??{}};for(let a of Ke)delete n[a];return n}function j6(o){let n={...o??{}};for(let a of Ve)delete n[a];return n}var qe="BUN_FEATURE_FLAG_NO_ORPHANS";function ye(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 w,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,[hre]:I}},onSpawn:(P)=>{if(w=P.pid,m==="stderr"||m==="both")be(P)},timeoutMs:se,waitForReady:(P,L)=>this.host.waitForReady(P,{signal:L,launchedProcess:{pid:w,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(w){if(!this.isIncompleteExtractionStartupError(w)||ie)throw w;if(ie=!0,!await this.removeIncompleteExtraction(S[0],w,s))throw w;({command:b,args:S,packageRunner:v}=this.host.withDaemonOptions(this.host.fallbackLauncher.resolveCommand(),c)),h(`Detected incomplete daemon package extraction (${Db}); 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=ye(process.env);if(this.host.recoveryOwner?.dbPath)n.AUTOMOBILE_DB_PATH=this.host.recoveryOwner.dbPath;if(n[Ub]=_d(),this.host.pidFilePath!==br)n[f.DAEMON_PID_FILE_PATH.name]=this.host.pidFilePath;if(this.host.lockFilePath!==JW)n[f.DAEMON_LOCK_FILE_PATH.name]=this.host.lockFilePath;if(this.host.socketPath!==Lt)n[f.DAEMON_SOCKET_PATH.name]=this.host.socketPath;if(o.toolOutputsDir)n[O4]=o.toolOutputsDir;return n}withDaemonOptions(o,n){let a=[...o.args,`${Zm}=${encodeURIComponent(this.host.socketPath)}`];return Qe(a,n),Ze(a,n),et(a,n),tt(a,n),rt(a,n),a.push(...pQ(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=Db;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(gK(),`daemon-launch-${process.pid}.log`)}async createDaemonExitFailure(o,n,a){let s=o===null?"unknown":o.toString(),c=n?`, signal ${n}`:"",d=o===AO?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 (${Db}). 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 ${AO}`)&&o.includes("incomplete package extraction")}isIncompleteExtractionStartupError(o){return o?.code===Db}describeError(o){return r(o)}async formatDaemonStartupFailure(o,n){let a=await this.readDaemonStartupLogExcerpt(n);if(a.length===0){if(n===Xe)return`${o}
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
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 ${ge} bytes):`,a].join(`
6
- `)}daemonLaunchLogLabel(){return Ef()==="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-ge),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 h(o){if(bJ()){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 ge=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(Vv,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(Vc,n.eventAllMarkers.join(","));else if(n.eventAllMarkersCliOverride)o.push(`${Vc}=`)}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 h(`Daemon readiness probe succeeded after ${this.host.timer.now()-c}ms (${u} polls; socket observed)`),!0;if(S==="aborted")return h(`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 h(`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 h(`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,st):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 h("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()+it;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 h("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!==YW||this.host.socketPath!==iB}async verifyDaemonConnection(o,n,a){let s=this.host.timer.now()+o;for(let c=1;c<=ez;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}/${ez}): ${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<ez&&u>0)await this.host.sleepUnlessAborted(Math.min(wre,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=nV(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 h(`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 h(`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,it=1000,st=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(_r(n)!==_r(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=Fi(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(){ki(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()+rn;while(this.host.remainingTime(d)>0){this.host.throwIfRecoveryCancelled(n);let u=this.host.remainingTime(d);h("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 h("Daemon started by another process"),"joined";if(this.host.throwIfRecoveryCancelled(n),this.host.acquireLock()){h("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,h("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),h("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}=ks(o);if(!Number.isSafeInteger(n)||n<=0)return{present:!0,livePid:void 0,token:a};return this.host.isProcessRunning(n)&&oP(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}=ks(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=Jg(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}=ks(o.trim());if(!Number.isSafeInteger(n)||n<=0)return null;if(!a)return null;let{logPath:s}=this.startupLockMetadata(a);if(!Dt(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 Rt,isAbsolute as kt}from"path";import{devNull as Ot}from"os";var yt=g({pid:T().int().positive().optional(),startedAt:T().finite().optional(),processGenerationToken:y().optional()}),gt=g({key:yt,attempts:T().int().positive().safe(),firstDeferredAtMs:T().min(-8640000000000000).max(8640000000000000)}),bt=3,St=60000,Pt=600000;function vt(o,n,a){let s=a-n.firstDeferredAtMs;return o==="active_operations"?s>=Pt:n.attempts>=bt||s>=St}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:_r(n)},c);if(!vt(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 ${$s()} --daemon restart\` to replace it once no device operation is active`;return e.warn(p),new xr(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=gt.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=f.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=fe(this.host.socketPath,this.host.seams.exitRecordFileSystem),a=De(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"&&kt(u)?Rt(u):u)}`).join(" ");return h(`Inheriting daemon port ${s.port??"default"} after ${n.reason}; flags: ${d||"none"}${c}`),s}async startUnlocked(o,n,a=!0){o=ns(o);let s=this.host.timer.now()+rn;if(!ul())await ll();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(XW,this.host.remainingTime(n))))return"joined";return this.host.startIdentityRecovery(o)}async takeOverOlderDaemon(o,n){if(Ore(o.version,ri))return h(`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<Ow)throw e.warn(`[DaemonManager] Skipping strictly-older daemon takeover due to cooldown: daemon ${o.version} is ${s}ms old, current version is ${ri}`),new xr("restart is in cooldown")}if(!await this.prepareOlderDaemonRestart(o))return{done:"joined"};this.host.takeoverDeferrals.clear();let a=ns(Object.fromEntries(Object.entries(n).filter(([,s])=>s!==void 0)));return n={...ns(o.options),...a,strictPort:!0},h(`Detected strictly older AutoMobile daemon version ${o.version} (PID ${o.pid}); stopping it before upgrade...`),await this.host.stopRunningDaemon(o,io,!1),await this.host.assertNoSurvivingDaemonBeforeRestart(n),await this.host.timer.sleep(dl),{options:n}}async prepareOlderDaemonRestart(o){let n;try{n=await this.host.prepareDaemonForConditionalRestart(o)}catch(c){if(c instanceof xr)this.deferOlderDaemonTakeover(o,"unavailable",c);throw c}if(n.accepted)return!0;if(n.reason==="generation_changed"||n.reason==="restart_pending")return h("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 xr(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){h(`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)h(` - PID ${m}`);let c=Math.min(XW,this.host.remainingTime(n)),d=await this.host.waitForExistingDaemon(c);if(this.host.throwIfRecoveryCancelled(a),d)return h("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 ${$s()} --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);h("Starting AutoMobile daemon...");let c=this.host.withDaemonOptions(this.host.resolveLaunchCommand(),o),d=this.host.daemonLaunchEnvironment(o),m=Ef(d),u=m!=="stderr",p=u?this.host.heldLockLogPath??this.host.daemonLaunchLogPath():Ot;if(d[yre]=u?p:"",await this.stampLaunchCheckoutVersion(d),u)gae(),vK(),Dre(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(XW,this.host.remainingTime(a)-Et);if(v>0&&await this.host.tryJoinPeerDaemonAfterSpawnExit(v))return h("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 h(`Daemon started successfully (PID ${b.pid}, port ${b.port})`),h(`Socket: ${b.socketPath}`),h(`Logs: ${p}`),"started"}}var Et=2000;import{readFile as jt}from"fs/promises";import{createHmac as ke,timingSafeEqual as At}from"crypto";var K6=f.DAEMON_LIVE_ACCEPTANCE_STARTUP_SECRET.name;function Oe(o){let n=_r(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 Tt(o,n){return ke("sha256",o).update(Ee(n)).digest("base64url")}function X(o,n,a){return ke("sha256",o).update(`${Ee(n)}\x00${Dr(a)}`).digest("base64url")}function t7(o,n,a,s){if(!o||typeof s!=="string")return!1;let c=Buffer.from(a===void 0?Tt(o,n):X(o,n,a)),d=Buffer.from(s);return d.length===c.length&&At(d,c)}function GH(o=process.env){let n=o[K6];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 xr("Provider identity changed before replacement");if(s&&o.hasPublishedRecoveryIdentity(c))return"joined";let d=ns({...c.options,...c.port===void 0?{}:{port:c.port}}),m=ns(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 Ft(o,c,u)}async function Ft(o,n,a){if(await o.awaitRestartCleanup([()=>n.running?o.stop(io,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(dl);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 xr)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 xr(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,io,!1);await o.sleep(dl);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 xr("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 xr(`maintenance admission is no longer valid (${c.reason??"unknown"})`);let d=M(ns(s.options),ns(Object.fromEntries(Object.entries(n).filter(([,m])=>m!==void 0))));return await o.stopRunningDaemon(s,io,!1),await o.sleep(dl),k(await o.startUnlocked(d,void 0,!1))}async function Te(o,n){let a=GH();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 Bt(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:_r(s)},S=await o.waitForStop(s.pid,HT,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 $t(o,d,s,m);throw b}finally{await Ut(o,d,p)}return await o.cleanupAcceptanceRestartFiles(s,D),await o.sleep(dl),k(await o.startUnlocked({...ns(s.options),strictPort:!0},void 0,!1))}async function xt(o,n,a,{generation:s,scope:c,startupSecret:d}){let u=await n.callDaemonMethod(zH,{...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(jH,{...a,restartToken:s}))?.committed!==!0)throw new t("Daemon acceptance-session restart admission expired before it could be committed.")}async function $t(o,n,a,s){try{await n.callDaemonMethod(KH,{...a,restartToken:s})}catch(c){e.warn(`Failed to explicitly roll back acceptance restart admission: ${r(c)}`)}}async function Ut(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 Bt(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),h("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(dl),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(_r(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":Ya(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=Ya(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),h(`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=ns(Object.fromEntries(Object.entries(n).filter(([,c])=>c!==void 0&&c!==!1)));return M(ns(a),s)}async readRecoveryOptionsFromPidFile(){try{let o=JSON.parse(await jt(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 Vt}from"fs";import{dirname as Kt}from"path";class G6{incumbent=null;supersededOwner=null;contenderEarlyOwner=null;sawLiveContender=!1;deps;constructor(o){this.deps={readPidFile:o?.readPidFile??(()=>Eo()),persistPidFile:o?.persistPidFile??zt,isProcessRunning:o?.isProcessRunning??((n)=>at(n,{debugLog:e.debug})),readProcessGenerationToken:o?.readProcessGenerationToken??Sa,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=Jt(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)||!qt(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)&&!Vw(o.pid,o,this.deps.readProcessGenerationToken,"the daemon PID record")}}function Jt(o){return{pid:o.pid,...wd(_r(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,...wd(_r(n))}}function qt(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 zt(o){Vt(Kt(br),{recursive:!0}),Cre(br,o)}class N extends Error{}class te{host;constructor(o){this.host=o}async stop(o=io,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),h("Daemon is not running");return}await this.host.stopRunningDaemon(a,o),O(this.host.socketPath,this.host.seams.exitRecordFileSystem)}async stopRunningDaemon(o,n=io,a=!0){this.assertDaemonStatusNamespace(o),h(`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(h("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,HT,c),m||=d.replacedByOtherGeneration,!d.stopped)throw new t(`Daemon process ${s} did not exit after SIGKILL`)}if(!m)await Bv({pidFilePath:this.host.pidFilePath,socketPaths:this.host.cleanupSocketPaths(o.socketPath),expectedPid:s});h("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:_r(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(),h(o.message);return}if(o instanceof Error&&o.message.includes("ESRCH")){await Bv({pidFilePath:this.host.pidFilePath,socketPaths:this.host.cleanupSocketPaths(n.socketPath),expectedPid:a}),h("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 Bv({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??nd,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;h(`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)){h(`Daemon candidate ${o.pid} exited before repair could stop it.`);return}this.host.throwIfRecoveryCancelled(a),h(`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(io,n),o)).stopped)return;if(h(`Verified daemon ${o.pid} did not stop gracefully, sending SIGKILL...`),!await this.host.verifyDaemonGenerationBeforeSignal(o,n)){h(`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(HT,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")){h(`Daemon candidate ${o.pid} exited before explicit restart could stop it.`);return}h(`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,io,o)).stopped)return;if(h(`Verified daemon ${o.pid} did not stop gracefully, sending SIGKILL...`),!await this.host.verifyDaemonGenerationBeforeSignal(o,void 0,"Explicit restart")){h(`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,HT,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(Zm))return!1;return this.host.matchesObservedDaemonGeneration(n,{pid:o.pid,ppid:0,command:"",startedAt:o.processStartedAt??o.startedAt,processGenerationToken:_r(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:_r(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&&Vw(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=wt("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:Ct(y(),y().min(1))}),x=g({accepted:ee(),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:f_,sockets:Ct(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 r7(o,n,a,s){if(!o)return!1;let c=a.readRecord();if(G(c,s)&&c.pid===n.pid&&c.startedAt===n.startedAt&&_r(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 xr?"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 xr(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(UH,{...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)=>h(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 Bv({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(HH,{pid:o.pid,startedAt:o.startedAt,...wd(_r(o)),version:o.version,buildId:o.buildId,entryScript:o.entryScript},{timeoutMs:er});if(!a||typeof a!=="object")throw new xr("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 xr("the daemon returned an unrecognized safe-restart admission result")}catch(a){if(a instanceof xr)throw a;throw new xr(`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 xr("incumbent database path or startup options unavailable");let n=this.host.createClient({clientIdentity:null}),a;try{let s=await n.callDaemonMethod(qH,{...o}),c=x.passthrough().parse(s);if(!c.accepted||typeof c.maintenanceToken!=="string")throw new xr(c.reason??"maintenance admission unavailable",c.reason);a=c.maintenanceToken;let d=await this.host.admitMaintenanceRestart(o,a);if(!d.accepted)throw new xr(d.reason??"maintenance admission refused",d.reason);return{accepted:!0}}finally{if(a)try{await n.callDaemonMethod(VH,{...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(WH,{pid:o.pid,startedAt:o.startedAt,...wd(_r(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 xr(`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 ju{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:lA,launchLogFileSystem:{openSync:ar,closeSync:ir},launchWorkingDirectory:gU,currentBuildId:()=>Ho().buildId,nextLaunchNonce:()=>B.next(),probeLaunchCheckoutVersion:LO};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:()=>Eo(this.pidFilePath),probe:()=>this.platform==="win32"?Promise.reject(Error("Failed to connect to daemon: socket-owner probing is unsupported on win32")):new Ia(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 dR({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:RD(),this.processSignaler=n.processSignaler,this.extractionCleaner=n.extractionCleaner,this.launchCommandResolver=n.launchCommandResolver,this.launcher=n.launcher??new $z({spawn:n.processSpawner?.spawn.bind(n.processSpawner),timer:n.timer}),this.fallbackLauncher=new $z({entryScript:null,spawn:n.processSpawner?.spawn.bind(n.processSpawner),timer:n.timer}),this.clientFactory=n.clientFactory??((a)=>new Ia(this.socketPath,void 0,n.timer,{recoveryOptions:{},clientIdentity:a?.clientIdentity})),this.daemonProtocolHealthProbe=n.daemonProtocolHealthProbe??(async()=>{try{return await new Ia(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=io,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=io,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 te(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 jC(`${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 Hae(o,n,a={}){return o4(o,n,a,ju)}function mr(o){let n=lr(o),{extractionCleaner:a=le,processSignaler:s=sr,idGenerator:c=B,platform:d=process.platform,portAvailabilityChecker:m=new jB,retryExecutor:u=new wn(n.timer),lockOwnerGenerationProbe:p=Ht}=o;return{...o,...n,extractionCleaner:a,processSignaler:s,idGenerator:c,platform:d,portAvailabilityChecker:m,retryExecutor:u,lockOwnerGenerationProbe:p}}function lr(o){let{stateProvider:n=()=>QL(R),timer:a=i,lockFilePath:s=JW,pidFilePath:c=br,socketPath:d=Lt,processFinder:m=RD()}=o;return{stateProvider:n,timer:a,lockFilePath:s,pidFilePath:c,socketPath:d,processFinder:m}}export{UH,HH,qH,VH,WH,zH,jH,KH,xr,kI,lA,e7,z6,ns,j6,K6,t7,GH,G6,r7,ju,Hae};
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
8
 
9
- //# debugId=D510D87404F1E00E64756E2164756E21
9
+ //# debugId=3127BDA02810C17C64756E2164756E21