@kaeawc/auto-mobile 0.0.90 → 0.0.92

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 (280) hide show
  1. package/README.md +7 -0
  2. package/README.md.backup +7 -0
  3. package/dist/build-info.json +12 -11
  4. package/dist/schemas/README.md +16 -0
  5. package/dist/schemas/prototype-icon-names.json +302 -0
  6. package/dist/schemas/prototype-platform-permissions.json +75 -0
  7. package/dist/schemas/test-plan.schema.json +2 -2
  8. package/dist/src/chunk-09442h7v.js +4 -0
  9. package/dist/src/chunk-0dfnyfkh.js +5 -0
  10. package/dist/src/chunk-0e4gm1kj.js +5 -0
  11. package/dist/src/chunk-0eb8576f.js +4 -0
  12. package/dist/src/chunk-0rjm4nx7.js +5 -0
  13. package/dist/src/chunk-0w1spptt.js +6 -0
  14. package/dist/src/chunk-1zmh2eak.js +4 -0
  15. package/dist/src/chunk-28k63ha3.js +5 -0
  16. package/dist/src/chunk-2d4wmp8b.js +4 -0
  17. package/dist/src/chunk-2e6s75qv.js +78 -0
  18. package/dist/src/chunk-2v7tw1nj.js +5 -0
  19. package/dist/src/chunk-32jpxz2y.js +323 -0
  20. package/dist/src/chunk-34zxqcmq.js +5 -0
  21. package/dist/src/chunk-3jmvqygr.js +238 -0
  22. package/dist/src/chunk-3swvfhqt.js +5 -0
  23. package/dist/src/chunk-44bt78m9.js +5 -0
  24. package/dist/src/chunk-488vt2bp.js +4 -0
  25. package/dist/src/chunk-4fgdhcwx.js +5 -0
  26. package/dist/src/chunk-4jp2se4w.js +4 -0
  27. package/dist/src/chunk-4pfftt07.js +5 -0
  28. package/dist/src/chunk-4vhr9e4t.js +4 -0
  29. package/dist/src/chunk-4xd6zs3y.js +15 -0
  30. package/dist/src/chunk-51567pg8.js +4 -0
  31. package/dist/src/chunk-5agqsfev.js +4 -0
  32. package/dist/src/chunk-5d706gmr.js +4 -0
  33. package/dist/src/chunk-5kd4rqk7.js +5 -0
  34. package/dist/src/chunk-5s645vr4.js +4 -0
  35. package/dist/src/chunk-61t538bm.js +4 -0
  36. package/dist/src/chunk-6d3mmqxt.js +54 -0
  37. package/dist/src/chunk-6hyt398x.js +5 -0
  38. package/dist/src/chunk-6mnr8kpm.js +4 -0
  39. package/dist/src/chunk-6pg7bqck.js +4 -0
  40. package/dist/src/chunk-79q5xsdc.js +42 -0
  41. package/dist/src/chunk-7bdgand3.js +4 -0
  42. package/dist/src/chunk-84cp9dw5.js +4 -0
  43. package/dist/src/chunk-86f2h5ww.js +5 -0
  44. package/dist/src/chunk-8cghfzb2.js +19 -0
  45. package/dist/src/chunk-8en08r7q.js +5 -0
  46. package/dist/src/chunk-950qcq1e.js +10 -0
  47. package/dist/src/chunk-9rkfyt6q.js +5 -0
  48. package/dist/src/chunk-9tf2p9y9.js +5 -0
  49. package/dist/src/chunk-9y5bcy28.js +6 -0
  50. package/dist/src/chunk-a2sc4jm0.js +5 -0
  51. package/dist/src/chunk-a4k9rt7z.js +5 -0
  52. package/dist/src/chunk-aa5ng3d1.js +4 -0
  53. package/dist/src/chunk-ajsrz473.js +5 -0
  54. package/dist/src/chunk-b3h0a6ca.js +4 -0
  55. package/dist/src/chunk-b4cxdzwy.js +20 -0
  56. package/dist/src/chunk-b6a737qt.js +4 -0
  57. package/dist/src/chunk-bn64x5z5.js +5 -0
  58. package/dist/src/chunk-bvh649za.js +12 -0
  59. package/dist/src/chunk-c9nk1r78.js +5 -0
  60. package/dist/src/chunk-c9tyfg4j.js +26 -0
  61. package/dist/src/chunk-cfsdfqnm.js +4 -0
  62. package/dist/src/chunk-cxyf04jc.js +7 -0
  63. package/dist/src/chunk-d57432wq.js +4 -0
  64. package/dist/src/chunk-da08tx5v.js +4 -0
  65. package/dist/src/chunk-eka89q3k.js +4 -0
  66. package/dist/src/chunk-f2tc08m2.js +4 -0
  67. package/dist/src/chunk-f8tnk179.js +5 -0
  68. package/dist/src/chunk-f9s1kkhx.js +5 -0
  69. package/dist/src/chunk-fbp8a4rx.js +4 -0
  70. package/dist/src/chunk-fd2z0sze.js +4 -0
  71. package/dist/src/chunk-fk927f4q.js +54 -0
  72. package/dist/src/chunk-fxmr3a0f.js +4 -0
  73. package/dist/src/chunk-gaqwhd44.js +4 -0
  74. package/dist/src/chunk-ggtd5x5a.js +5 -0
  75. package/dist/src/chunk-gndcfrm7.js +4 -0
  76. package/dist/src/chunk-h3n4adc6.js +310 -0
  77. package/dist/src/chunk-h5pjbb83.js +4 -0
  78. package/dist/src/chunk-hgnnh302.js +4 -0
  79. package/dist/src/chunk-hmke8nhx.js +5 -0
  80. package/dist/src/chunk-j2bx12hn.js +4 -0
  81. package/dist/src/chunk-j70y1a2g.js +4 -0
  82. package/dist/src/chunk-jdqvcq0a.js +5 -0
  83. package/dist/src/chunk-jhnbfj19.js +55 -0
  84. package/dist/src/chunk-js1jpyxp.js +6 -0
  85. package/dist/src/chunk-kbjq0qvb.js +4 -0
  86. package/dist/src/chunk-kfwx57xd.js +4 -0
  87. package/dist/src/chunk-km0dy5vc.js +71 -0
  88. package/dist/src/chunk-kzwctna2.js +4 -0
  89. package/dist/src/chunk-m9ehyehy.js +4 -0
  90. package/dist/src/chunk-mct91p1f.js +4 -0
  91. package/dist/src/chunk-mf9spd4g.js +5 -0
  92. package/dist/src/chunk-mgrcansb.js +4 -0
  93. package/dist/src/chunk-mqc1d0eb.js +6 -0
  94. package/dist/src/chunk-n1zmpk0z.js +4 -0
  95. package/dist/src/chunk-ncyjf63g.js +4 -0
  96. package/dist/src/chunk-nr64d21q.js +973 -0
  97. package/dist/src/chunk-nwm2pq5v.js +168 -0
  98. package/dist/src/chunk-pm06b05d.js +9 -0
  99. package/dist/src/chunk-q50s00ry.js +4 -0
  100. package/dist/src/chunk-qv2918jt.js +4 -0
  101. package/dist/src/chunk-qwye1958.js +14 -0
  102. package/dist/src/chunk-r0f1q783.js +5 -0
  103. package/dist/src/chunk-r14wwk37.js +18 -0
  104. package/dist/src/chunk-r20pe1nv.js +5 -0
  105. package/dist/src/chunk-r8z9pfve.js +5 -0
  106. package/dist/src/chunk-rdpgkjf6.js +4 -0
  107. package/dist/src/chunk-rkr0dks9.js +5 -0
  108. package/dist/src/chunk-rn84t3sf.js +11 -0
  109. package/dist/src/chunk-s123kn7n.js +4 -0
  110. package/dist/src/chunk-s1zq65ny.js +4 -0
  111. package/dist/src/chunk-s73qn3fx.js +4 -0
  112. package/dist/src/chunk-sjn0nj4p.js +5 -0
  113. package/dist/src/chunk-sns0c35v.js +7 -0
  114. package/dist/src/chunk-stfzjr9y.js +8 -0
  115. package/dist/src/chunk-sz1a7p43.js +4 -0
  116. package/dist/src/chunk-t4dr5c8v.js +8 -0
  117. package/dist/src/chunk-tc8k9c1j.js +4 -0
  118. package/dist/src/chunk-teznhase.js +4 -0
  119. package/dist/src/chunk-ty9xgmz4.js +4 -0
  120. package/dist/src/chunk-tyazf3sk.js +145 -0
  121. package/dist/src/chunk-v6npjrjm.js +5 -0
  122. package/dist/src/chunk-v90es00d.js +4 -0
  123. package/dist/src/chunk-vbvtzkwz.js +5 -0
  124. package/dist/src/chunk-vefd8qee.js +8 -0
  125. package/dist/src/chunk-vs9r72ta.js +17 -0
  126. package/dist/src/chunk-w2mwa0jk.js +4 -0
  127. package/dist/src/chunk-w7zsh13a.js +9 -0
  128. package/dist/src/chunk-w88k0bgr.js +4 -0
  129. package/dist/src/chunk-wry6skrm.js +4 -0
  130. package/dist/src/chunk-wzdt0enk.js +4 -0
  131. package/dist/src/chunk-xhhv854c.js +4 -0
  132. package/dist/src/chunk-y58270hd.js +4 -0
  133. package/dist/src/chunk-yk0hmbex.js +4 -0
  134. package/dist/src/chunk-ympy4fdz.js +28 -0
  135. package/dist/src/chunk-yw436axy.js +4 -0
  136. package/dist/src/chunk-z04jrpjy.js +5 -0
  137. package/dist/src/chunk-z2xznczw.js +4 -0
  138. package/dist/src/chunk-z4xnrgps.js +4 -0
  139. package/dist/src/chunk-z7csyszv.js +4 -0
  140. package/dist/src/chunk-z8t0v07j.js +11 -0
  141. package/dist/src/chunk-z916af47.js +228 -0
  142. package/dist/src/chunk-zcr8he8q.js +5 -0
  143. package/dist/src/chunk-zd9vmkzn.js +9 -0
  144. package/dist/src/chunk-zg67wjkh.js +5 -0
  145. package/dist/src/chunk-zj939v0h.js +5 -0
  146. package/dist/src/chunk-zkdjwtc1.js +4 -0
  147. package/dist/src/chunk-zkv5kzt6.js +4 -0
  148. package/dist/src/daemon/processEntry.js +4 -0
  149. package/dist/src/index.js +4 -2797
  150. package/dist/src/runtime/bunRuntimeGuard.js +4 -0
  151. package/dist/src/utils/workers/iosBundleExtractWorker.js +2 -3
  152. package/node_modules/strtok3/lib/BufferSizeError.js +1 -1
  153. package/node_modules/strtok3/lib/TokenWriter.js +151 -0
  154. package/node_modules/strtok3/lib/core.js +1 -0
  155. package/node_modules/strtok3/package.json +2 -2
  156. package/node_modules/token-types/LICENSE.txt +9 -9
  157. package/node_modules/token-types/{lib → dist/lib}/index.js +21 -3
  158. package/node_modules/token-types/package.json +81 -81
  159. package/package.json +10 -10
  160. package/schemas/README.md +16 -0
  161. package/schemas/prototype-icon-names.json +302 -0
  162. package/schemas/prototype-platform-permissions.json +75 -0
  163. package/schemas/test-plan.schema.json +2 -2
  164. package/node_modules/@borewit/text-codec/README.md +0 -87
  165. package/node_modules/@jimp/diff/node_modules/pixelmatch/README.md +0 -110
  166. package/node_modules/@jimp/diff/node_modules/pixelmatch/node_modules/pngjs/README.md +0 -433
  167. package/node_modules/@jimp/file-ops/dist/browser/index.js +0 -8
  168. package/node_modules/@jimp/js-png/README.md +0 -35
  169. package/node_modules/@jimp/js-png/src/__image_snapshots__/index-node-test-ts-png-should-use-png-options-1-snap.png +0 -0
  170. package/node_modules/@jimp/js-png/src/output.png +0 -0
  171. package/node_modules/@jimp/js-png/vitest.config.browser.mjs +0 -3
  172. package/node_modules/@jimp/plugin-resize/README.md +0 -12
  173. package/node_modules/@jimp/plugin-resize/vitest.config.browser.mjs +0 -3
  174. package/node_modules/@tokenizer/inflate/README.md +0 -114
  175. package/node_modules/@tokenizer/token/README.md +0 -19
  176. package/node_modules/await-to-js/README.md +0 -82
  177. package/node_modules/debug/README.md +0 -481
  178. package/node_modules/exif-parser/README.md +0 -83
  179. package/node_modules/file-type/readme.md +0 -667
  180. package/node_modules/ieee754/README.md +0 -51
  181. package/node_modules/mime/README.md +0 -178
  182. package/node_modules/ms/readme.md +0 -59
  183. package/node_modules/parse-bmfont-xml/README.md +0 -74
  184. package/node_modules/parse-bmfont-xml/lib/browser.js +0 -85
  185. package/node_modules/parse-bmfont-xml/node_modules/xml2js/README.md +0 -507
  186. package/node_modules/pngjs/README.md +0 -287
  187. package/node_modules/sax/README.md +0 -228
  188. package/node_modules/strtok3/README.md +0 -736
  189. package/node_modules/tinycolor2/README.md +0 -492
  190. package/node_modules/tinycolor2/cjs/test.js +0 -2191
  191. package/node_modules/tinycolor2/cjs/test_template.js +0 -26
  192. package/node_modules/tinycolor2/deno_asserts@0.168.0.mjs +0 -807
  193. package/node_modules/tinycolor2/esm/test.js +0 -2189
  194. package/node_modules/tinycolor2/esm/test_template.js +0 -24
  195. package/node_modules/tinycolor2/tinycolor.js +0 -1191
  196. package/node_modules/token-types/README.md +0 -120
  197. package/node_modules/uint8array-extras/readme.md +0 -318
  198. package/node_modules/xml-parse-from-string/README.md +0 -35
  199. package/node_modules/xmlbuilder/README.md +0 -86
  200. package/node_modules/zod/README.md +0 -208
  201. package/node_modules/zod/v4/locales/ar.d.cts +0 -4
  202. package/node_modules/zod/v4/locales/ar.d.ts +0 -4
  203. package/node_modules/zod/v4/locales/az.d.cts +0 -4
  204. package/node_modules/zod/v4/locales/az.d.ts +0 -4
  205. package/node_modules/zod/v4/locales/be.d.cts +0 -4
  206. package/node_modules/zod/v4/locales/be.d.ts +0 -4
  207. package/node_modules/zod/v4/locales/ca.d.cts +0 -4
  208. package/node_modules/zod/v4/locales/ca.d.ts +0 -4
  209. package/node_modules/zod/v4/locales/cs.d.cts +0 -4
  210. package/node_modules/zod/v4/locales/cs.d.ts +0 -4
  211. package/node_modules/zod/v4/locales/de.d.cts +0 -4
  212. package/node_modules/zod/v4/locales/de.d.ts +0 -4
  213. package/node_modules/zod/v4/locales/en.d.cts +0 -5
  214. package/node_modules/zod/v4/locales/en.d.ts +0 -5
  215. package/node_modules/zod/v4/locales/eo.d.cts +0 -5
  216. package/node_modules/zod/v4/locales/eo.d.ts +0 -5
  217. package/node_modules/zod/v4/locales/es.d.cts +0 -4
  218. package/node_modules/zod/v4/locales/es.d.ts +0 -4
  219. package/node_modules/zod/v4/locales/fa.d.cts +0 -4
  220. package/node_modules/zod/v4/locales/fa.d.ts +0 -4
  221. package/node_modules/zod/v4/locales/fi.d.cts +0 -4
  222. package/node_modules/zod/v4/locales/fi.d.ts +0 -4
  223. package/node_modules/zod/v4/locales/fr-CA.d.cts +0 -4
  224. package/node_modules/zod/v4/locales/fr-CA.d.ts +0 -4
  225. package/node_modules/zod/v4/locales/fr.d.cts +0 -4
  226. package/node_modules/zod/v4/locales/fr.d.ts +0 -4
  227. package/node_modules/zod/v4/locales/he.d.cts +0 -4
  228. package/node_modules/zod/v4/locales/he.d.ts +0 -4
  229. package/node_modules/zod/v4/locales/hu.d.cts +0 -4
  230. package/node_modules/zod/v4/locales/hu.d.ts +0 -4
  231. package/node_modules/zod/v4/locales/id.d.cts +0 -4
  232. package/node_modules/zod/v4/locales/id.d.ts +0 -4
  233. package/node_modules/zod/v4/locales/index.d.cts +0 -39
  234. package/node_modules/zod/v4/locales/index.d.ts +0 -39
  235. package/node_modules/zod/v4/locales/it.d.cts +0 -4
  236. package/node_modules/zod/v4/locales/it.d.ts +0 -4
  237. package/node_modules/zod/v4/locales/ja.d.cts +0 -4
  238. package/node_modules/zod/v4/locales/ja.d.ts +0 -4
  239. package/node_modules/zod/v4/locales/kh.d.cts +0 -4
  240. package/node_modules/zod/v4/locales/kh.d.ts +0 -4
  241. package/node_modules/zod/v4/locales/ko.d.cts +0 -4
  242. package/node_modules/zod/v4/locales/ko.d.ts +0 -4
  243. package/node_modules/zod/v4/locales/mk.d.cts +0 -4
  244. package/node_modules/zod/v4/locales/mk.d.ts +0 -4
  245. package/node_modules/zod/v4/locales/ms.d.cts +0 -4
  246. package/node_modules/zod/v4/locales/ms.d.ts +0 -4
  247. package/node_modules/zod/v4/locales/nl.d.cts +0 -4
  248. package/node_modules/zod/v4/locales/nl.d.ts +0 -4
  249. package/node_modules/zod/v4/locales/no.d.cts +0 -4
  250. package/node_modules/zod/v4/locales/no.d.ts +0 -4
  251. package/node_modules/zod/v4/locales/ota.d.cts +0 -4
  252. package/node_modules/zod/v4/locales/ota.d.ts +0 -4
  253. package/node_modules/zod/v4/locales/pl.d.cts +0 -4
  254. package/node_modules/zod/v4/locales/pl.d.ts +0 -4
  255. package/node_modules/zod/v4/locales/ps.d.cts +0 -4
  256. package/node_modules/zod/v4/locales/ps.d.ts +0 -4
  257. package/node_modules/zod/v4/locales/pt.d.cts +0 -4
  258. package/node_modules/zod/v4/locales/pt.d.ts +0 -4
  259. package/node_modules/zod/v4/locales/ru.d.cts +0 -4
  260. package/node_modules/zod/v4/locales/ru.d.ts +0 -4
  261. package/node_modules/zod/v4/locales/sl.d.cts +0 -4
  262. package/node_modules/zod/v4/locales/sl.d.ts +0 -4
  263. package/node_modules/zod/v4/locales/sv.d.cts +0 -4
  264. package/node_modules/zod/v4/locales/sv.d.ts +0 -4
  265. package/node_modules/zod/v4/locales/ta.d.cts +0 -4
  266. package/node_modules/zod/v4/locales/ta.d.ts +0 -4
  267. package/node_modules/zod/v4/locales/th.d.cts +0 -4
  268. package/node_modules/zod/v4/locales/th.d.ts +0 -4
  269. package/node_modules/zod/v4/locales/tr.d.cts +0 -5
  270. package/node_modules/zod/v4/locales/tr.d.ts +0 -5
  271. package/node_modules/zod/v4/locales/ua.d.cts +0 -4
  272. package/node_modules/zod/v4/locales/ua.d.ts +0 -4
  273. package/node_modules/zod/v4/locales/ur.d.cts +0 -4
  274. package/node_modules/zod/v4/locales/ur.d.ts +0 -4
  275. package/node_modules/zod/v4/locales/vi.d.cts +0 -4
  276. package/node_modules/zod/v4/locales/vi.d.ts +0 -4
  277. package/node_modules/zod/v4/locales/zh-CN.d.cts +0 -4
  278. package/node_modules/zod/v4/locales/zh-CN.d.ts +0 -4
  279. package/node_modules/zod/v4/locales/zh-TW.d.cts +0 -4
  280. package/node_modules/zod/v4/locales/zh-TW.d.ts +0 -4
@@ -0,0 +1,5 @@
1
+ // @bun
2
+ import{i,l,e}from"./chunk-z8t0v07j.js";import{ge,Fm}from"./chunk-h3n4adc6.js";import{gQ}from"./chunk-6d3mmqxt.js";import{mJ,kl,El,qO,Ka,iP}from"./chunk-ympy4fdz.js";import{oJ,aJ}from"./chunk-6hyt398x.js";var w=1500,R={shutdownInventoryReads:()=>{Fm()},stopAcceptingVideoRecordingStarts:mJ,listActiveVideoRecordings:Ka,listOwnedActiveVideoRecordingIds:iP,stopVideoRecording:kl,forceStopVideoRecording:qO,interruptVideoRecording:El,shutdownIOSCtrlProxies:()=>ge.shutdownAll(),stopWatchRunners:oJ,stopTvosRunners:aJ,stopVisionosRunners:gQ};async function i2(r=R){r.shutdownInventoryReads?.(),r.stopWatchRunners(),r.stopTvosRunners?.(),r.stopVisionosRunners?.();let n=r.timer??i,t=r.timeoutMs??w,c=new Set;try{let o=await a(r.stopAcceptingVideoRecordingStarts(),n,t);if(o.status!=="fulfilled")e.warn(`[Daemon] Failed to quiesce recording starts during shutdown: ${o.error}`);let d=await a(r.listActiveVideoRecordings(),n,t);if(d.status==="fulfilled")for(let m of d.value)c.add(m.recordingId);else e.warn(`[Daemon] Failed to list active recordings during shutdown: ${d.error}`)}catch(o){e.warn(`[Daemon] Failed to list active recordings during shutdown: ${o}`)}h(r,c);let u=a(r.shutdownIOSCtrlProxies(),n,t);await Promise.all(Array.from(c,async(o)=>{try{let d=r.stopVideoRecording(o),m=await a(d,n,t);if(m.status==="fulfilled")return;e.warn(`[Daemon] Failed to stop recording ${o} during shutdown: ${m.error}`);let f=await a(r.forceStopVideoRecording(o),n,t);if(f.status!=="fulfilled")e.warn(`[Daemon] Failed to force-stop recording ${o} during shutdown: ${f.error}`);try{await d;return}catch(g){e.warn(`[Daemon] Recording ${o} did not finish after force-stop: ${g}`)}let p=await a(r.interruptVideoRecording(o),n,t);if(p.status!=="fulfilled")e.warn(`[Daemon] Failed to interrupt recording ${o} during shutdown: ${p.error}`)}catch(d){e.warn(`[Daemon] Unexpected recording cleanup error during shutdown: ${d}`)}}));let s=await u;if(s.status!=="fulfilled")e.warn(`[Daemon] Failed to stop iOS CtrlProxy instances during shutdown: ${s.error}`)}function h(r,n){try{for(let t of r.listOwnedActiveVideoRecordingIds())n.add(t)}catch(t){e.warn(`[Daemon] Failed to list in-memory recordings during shutdown: ${t}`)}}async function a(r,n,t){let c=r.then((o)=>({status:"fulfilled",value:o}),(o)=>({status:"failed",error:o})),u=Error(`timed out after ${t}ms`),s=await l(c,{timer:n,timeoutMs:t,label:"Child process cleanup",timeoutError:()=>u}).then((o)=>({value:o}),(o)=>({error:o}));if("value"in s)return s.value;if(s.error===u)return{status:"failed",error:s.error};throw s.error}
3
+ export{i2};
4
+
5
+ //# debugId=8043469C104BA8A564756E2164756E21
@@ -0,0 +1,9 @@
1
+ // @bun
2
+ import{i,lb,g$,hd,Ae,Zj,Qie,e2,Bt,tf,l,nt,FY,e}from"./chunk-z8t0v07j.js";import{g}from"./chunk-mf9spd4g.js";import{p6,xc,SZ}from"./chunk-nwm2pq5v.js";import{w,QF,Cr,QQ,Vc,iL,Ct,FV,vr,LV,tee,Jr,BV,Xi,lT,hC,ree,nee,Xd,rw,HV,oee,ei,Zd,Qd,hee,gee,pv,So,pw,yee,hn,yv,Os,Cw,kW,Em,CL,_5,FC,jL}from"./chunk-h3n4adc6.js";import{No,fe,LI,tq,ya}from"./chunk-8cghfzb2.js";import{L,ad,Ir,Ba,la,Nt,Pg,Ss,kR,_i,vi,nb,LD}from"./chunk-32jpxz2y.js";import{y,A,Z,f,kt,ee,P}from"./chunk-79q5xsdc.js";import{sC}from"./chunk-6d3mmqxt.js";import{BG}from"./chunk-vs9r72ta.js";import{Pc}from"./chunk-0dfnyfkh.js";import{r,t}from"./chunk-9rkfyt6q.js";import{vt}from"./chunk-2v7tw1nj.js";var $1="ide/republishIdentity",U1="ide/prepareRestart",H1="ide/prepareMaintenance",q1="ide/completeMaintenance",V1="ide/restartAdmitted",W1="ide/restartAcceptanceSession",z1="ide/commitAcceptanceRestart",j1="ide/releaseAcceptanceRestart",ce=1000;class _r extends fe{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 YE(o){return{error:{code:o.code,message:o.message,retryable:o.retryable,retryAfterMs:o.retryAfterMs}}}import{createServer as rr}from"net";import{rm as Me}from"fs/promises";import{resolve as de,sep as M}from"path";import{tmpdir as xe}from"os";function me(o){let a=de(o).split(M),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(M)||M;if(d===M)return null;let m=de(xe());if(!Pc(m,d,{allowEqual:!1}))return null;return d}var le={async removeExtractionForEntryScript(o){let n=me(o);if(!n)return!1;return await Me(n,{recursive:!0,force:!0}),!0}};import{readFileSync as Ne,rmSync as Ge,writeFileSync as He}from"fs";var DP={readFileSync:Ne,writeFileSync:He,rmSync:Ge},pe=1800000,$e=f({reason:P(["orphan-watchdog","database-health","startup-failure","unexpected-exit"]),exitedAtMs:A().finite(),buildId:y(),options:LI});function U(o){return`${o}.exit-record.json`}function cX(o,n,a=DP){try{a.writeFileSync(U(o),JSON.stringify(n))}catch(s){e.warn(`Failed to record daemon self-exit: ${r(s)}`,s)}}function E(o,n=DP){try{n.rmSync(U(o),{force:!0})}catch(a){e.warn(`Failed to remove daemon exit record: ${r(a)}`,a)}}function he(o,n=DP){let a=U(o),s;try{s=n.readFileSync(a,"utf8")}catch(c){e.debug(`No daemon exit record at ${a}: ${r(c)}`);return}E(o,n);try{let c=JSON.parse(s),d=$e.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 B(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:B(u,m),outcome:"inherited",inheritedPort:d.port===void 0&&u.port!==void 0}}class AG{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 or,openSync as nr,closeSync as ar}from"fs";import{existsSync as Ue,readFileSync as Be}from"fs";class W{host;constructor(o){this.host=o}cleanupSocketPaths(o){if(this.host.pidFilePath===vr)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:CL(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(Em))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(Em))?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:Ir(a)});return n.filter((s)=>{let c=this.host.hasNamespaceRecordOrMarker(s)||!s.command.includes(Em)&&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=Bt(nee),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(hC,p))).map((D)=>D.pid)},{maxAttempts:ree,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,...We])];return this.degradedStartProbePorts(o).flatMap((a)=>n.map((s)=>({host:s,port:a})))}degradedStartProbePorts(o){let n=o.port??Vc,a=[n];if(Vc!==n)a.push(Vc);let s=this.readPersistedDaemonOwnerPortForStart();if(s!==void 0&&!a.includes(s))a.push(s);return a}readPersistedDaemonOwnerPortForStart(){if(!Ue(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(Be(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(_5(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",We=["127.0.0.1","::1"];import{readFile as dt}from"fs/promises";import{constants as Se,openSync as mt,closeSync as lt,fstatSync as ut,readFileSync as Pe,writeSync as pt}from"fs";import{basename as ht,isAbsolute as ft}from"path";import{open as qe}from"fs/promises";import{join as ze}from"path";import{devNull as Ye}from"os";var je=["enabledTools","disabledTools","toolResultsNoStructuredContent","actionsCompactMetadata"],Ke=["toolResultsNoStructuredContent","actionsCompactMetadata"],Ve=[g.ENABLED_TOOLS.name,g.DISABLED_TOOLS.name,"AUTOMOBILE_TOOL_RESULTS_NO_STRUCTURED_CONTENT","AUTOMOBILE_ACTIONS_COMPACT_METADATA"];function Yo(o){let n={...o??{}};for(let a of Ke)delete n[a];return n}function TG(o){let n={...o??{}};for(let a of je)delete n[a];return n}var Je="BUN_FEATURE_FLAG_NO_ORPHANS";function ye(o){let n={...o};for(let a of[...Ve,Je])delete n[a];return n}class K{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:R}=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 k,_=R?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,[QQ]:_}},onSpawn:(v)=>{if(k=v.pid,m==="stderr"||m==="both")be(v)},timeoutMs:se,waitForReady:(v,F)=>this.host.waitForReady(v,{signal:F,launchedProcess:{pid:k,launchNonce:_}}),isReadyForLaunchedProcess:(v,F,_e)=>this.host.isLaunchedProcessReady(v,F,_e,_),formatFailure:(v)=>this.createDaemonStartupFailure(v,D),formatExitFailure:(v,F)=>this.host.createDaemonExitFailure(v,F,D)});break}catch(k){if(!this.isIncompleteExtractionStartupError(k)||ie)throw k;if(ie=!0,!await this.removeIncompleteExtraction(S[0],k,s))throw k;({command:b,args:S,packageRunner:R}=this.host.withDaemonOptions(this.host.fallbackLauncher.resolveCommand(),c)),h(`Detected incomplete daemon package extraction (${nb}); 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[lb]=hd(),this.host.pidFilePath!==vr)n[g.DAEMON_PID_FILE_PATH.name]=this.host.pidFilePath;if(this.host.lockFilePath!==LV)n[g.DAEMON_LOCK_FILE_PATH.name]=this.host.lockFilePath;if(this.host.socketPath!==Ct)n[g.DAEMON_SOCKET_PATH.name]=this.host.socketPath;if(o.toolOutputsDir)n[p6]=o.toolOutputsDir;return n}withDaemonOptions(o,n){let a=[...o.args,`${Em}=${encodeURIComponent(this.host.socketPath)}`];return Xe(a,n),Qe(a,n),Ze(a,n),et(a,n),tt(a,n),a.push(...SZ(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=nb;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 ze(Zj(),`daemon-launch-${process.pid}.log`)}async createDaemonExitFailure(o,n,a){let s=o===null?"unknown":o.toString(),c=n?`, signal ${n}`:"",d=o===LD?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 (${nb}). 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 ${LD}`)&&o.includes("incomplete package extraction")}isIncompleteExtractionStartupError(o){return o?.code===nb}describeError(o){return r(o)}async formatDaemonStartupFailure(o,n){let a=await this.readDaemonStartupLogExcerpt(n);if(a.length===0){if(n===Ye)return`${o}
4
+ Daemon stderr was relayed to the configured process sink; file capture is disabled.`;return`${o}
5
+ Logs: ${n} (empty)`}return[o,`Logs: ${n}`,`${this.daemonLaunchLogLabel()} (last ${ge} bytes):`,a].join(`
6
+ `)}daemonLaunchLogLabel(){return tf()==="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 qe(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(FY()){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 Xe(o,n){if(n.port)o.push("--port",n.port.toString());if(n.host)o.push("--host",n.host);if(C(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(yv,n.runnerReadinessTimeoutMs.toString())}function Qe(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 Ze(o,n){C(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(xc,n.eventAllMarkers.join(","));else if(n.eventAllMarkersCliOverride)o.push(`${xc}=`)}function et(o,n){C(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 tt(o,n){if(C(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);C(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 C(o,n){for(let[a,s]of n)if(a)o.push(s)}import{existsSync as rt}from"fs";class V{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()+T),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)}`)}},st);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(T,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()+at;if(!s){let p=Math.min(T,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(ot,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"||rt(this.host.socketPath)}isIsolatedSocketNamespace(){return this.host.pidFilePath!==FV||this.host.socketPath!==iL}async verifyDaemonConnection(o,n,a){let s=this.host.timer.now()+o;for(let c=1;c<=HV;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}/${HV}): ${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<HV&&u>0)await this.host.sleepUnlessAborted(Math.min(oee,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=tq(p,this.host.socketPath),b=ct(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 T=1000,ot=100,at=1000,it=2000,st=100;function ct(o,n){if(n.pid!==o.pid)return"pid";if(o.startedAt===void 0||n.startedAt!==o.startedAt)return"startedAt";if(Ir(n)!==Ir(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=_i(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(){vi(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()+Jr;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(T,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=Pe(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}=Ss(o);if(!Number.isSafeInteger(n)||n<=0)return{present:!0,livePid:void 0,token:a};return this.host.isProcessRunning(n)&&kR(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(T,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:Se.O_NOFOLLOW,unsafeWriteMask:18},s;try{s=mt(this.host.lockFilePath,Se.O_RDWR|n,384)}catch(c){e.warn("Failed to safely open startup lock for identity recovery",c);return}try{let c=ut(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=Pe(s,"utf8"),{pid:u,token:p,metadata:D,generation:b}=Ss(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}),R=Pg(u,p,S,b);pt(s,R.padEnd(Buffer.byteLength(m)),0,"utf8")}finally{lt(s)}}async getLockHolderStartupLogPath(){try{let o=await dt(this.host.lockFilePath,"utf-8"),{pid:n,metadata:a}=Ss(o.trim());if(!Number.isSafeInteger(n)||n<=0)return null;if(!a)return null;let{logPath:s}=this.startupLockMetadata(a);if(!ft(s)||ht(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 wt}from"path";import{devNull as Ot}from"os";var Dt=f({pid:A().int().positive().optional(),startedAt:A().finite().optional(),processGenerationToken:y().optional()}),yt=f({key:Dt,attempts:A().int().positive().safe(),firstDeferredAtMs:A().min(-8640000000000000).max(8640000000000000)}),gt=3,bt=60000,St=600000;function Pt(o,n,a){let s=a-n.firstDeferredAtMs;return o==="active_operations"?s>=St:n.attempts>=gt||s>=bt}function I({ledger:o,incumbent:n,kind:a,original:s,nowMs:c,subject:d}){let m=o.recordDeferral({pid:n.pid,startedAt:n.startedAt,processGenerationToken:Ir(n)},c);if(!Pt(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 ${Os()} --daemon restart\` to replace it once no device operation is active`;return e.warn(p),new _r(p)}function ve(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&&ve(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||!ve(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=yt.safeParse(n);return a.success?a.data:void 0}catch(o){e.warn(`Failed to read takeover deferral ledger: ${r(o)}`,o);return}}}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=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"&&wt(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=Yo(o);let s=this.host.timer.now()+Jr;if(!Qd())await Zd();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(BV,this.host.remainingTime(n))))return"joined";return this.host.startIdentityRecovery(o)}async takeOverOlderDaemon(o,n){if(yee(o.version,ei))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<rw)throw e.warn(`[DaemonManager] Skipping strictly-older daemon takeover due to cooldown: daemon ${o.version} is ${s}ms old, current version is ${ei}`),new _r("restart is in cooldown")}if(!await this.prepareOlderDaemonRestart(o))return{done:"joined"};this.host.takeoverDeferrals.clear();let a=Yo(Object.fromEntries(Object.entries(n).filter(([,s])=>s!==void 0)));return n={...Yo(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,Xi,!1),await this.host.assertNoSurvivingDaemonBeforeRestart(n),await this.host.timer.sleep(Xd),{options:n}}async prepareOlderDaemonRestart(o){let n;try{n=await this.host.prepareDaemonForConditionalRestart(o)}catch(c){if(c instanceof _r)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 _r(s))}deferOlderDaemonTakeover(o,n,a){throw I({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(BV,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 ${Os()} --daemon restart\` explicitly.`)}return!1}async launchDaemon(o,n,a,s){if(n)o=await this.host.inheritExitSettings(o);else E(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=tf(d),u=m!=="stderr",p=u?this.host.heldLockLogPath??this.host.daemonLaunchLogPath():Ot;if(d[tee]=u?p:"",u)Qie(),e2(),gee(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 R=Math.min(BV,this.host.remainingTime(a)-Et);if(R>0&&await this.host.tryJoinPeerDaemonAfterSpawnExit(R))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 Wt}from"fs/promises";import{createHmac as Re,timingSafeEqual as Lt}from"crypto";var kG=g.DAEMON_LIVE_ACCEPTANCE_STARTUP_SECRET.name;function we(o){let n=Ir(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 ke(o){return["auto-mobile-live-acceptance-capability-v1",o.pid,o.startedAt,o.processGenerationToken??"",o.version,o.buildId,o.entryScript].join("\x00")}function At(o,n){return Re("sha256",o).update(ke(n)).digest("base64url")}function X(o,n,a){return Re("sha256",o).update(`${ke(n)}\x00${Cr(a)}`).digest("base64url")}function dX(o,n,a,s){if(!o||typeof s!=="string")return!1;let c=Buffer.from(a===void 0?At(o,n):X(o,n,a)),d=Buffer.from(s);return d.length===c.length&&Lt(d,c)}function K1(o=process.env){let n=o[kG];return n&&n.length>=32?n:void 0}function O(o){return o==="joined"?"joined":"restarted"}function x(o,n){return{...B(o,n),strictPort:!0}}async function Oe(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 _r("Provider identity changed before replacement");if(s&&o.hasPublishedRecoveryIdentity(c))return"joined";let d=Yo({...c.options,...c.port===void 0?{}:{port:c.port}}),m=Yo(Object.fromEntries(Object.entries(n).filter(([,p])=>p!==void 0))),u=x(d,m);if(a&&!o.isSameDaemonGeneration(c,a))return o.log("Daemon generation changed before restart; joining the current generation"),"joined";if(a)return It(o,c,a,{options:u,recovering:s});return Tt(o,c,u)}async function Tt(o,n,a){if(await o.awaitRestartCleanup([()=>n.running?o.stop(Xi,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(Xd);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 O(s)}async function Ft(o,n,a){let s;try{s=a?await o.prepareIdentityRecoveryRestart(n):await o.prepareDaemonForConditionalRestart(n)}catch(m){if(m instanceof _r)throw I({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 I({ledger:o.takeoverDeferrals,incumbent:n,kind:c,original:new _r(d),nowMs:o.now(),subject:"daemon"})}async function It(o,n,a,{options:s,recovering:c}){if(!await Ft(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,Xi,!1);await o.sleep(Xd);let d=c?await o.startUnlocked(s,void 0,!n.running):n.running?await o.startWithRunningOptions(s):await o.start(s);return O(d)}async function Ee(o,n,a){if(!a)throw new t("restart-admitted requires a maintenance admission token.");if(!o.acquireLock())throw new _r("another daemon lifecycle transition is in progress");try{return await _t(o,n,a)}finally{o.releaseLock()}}async function _t(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 _r(`maintenance admission is no longer valid (${c.reason??"unknown"})`);let d=x(Yo(s.options),Yo(Object.fromEntries(Object.entries(n).filter(([,m])=>m!==void 0))));return await o.stopRunningDaemon(s,Xi,!1),await o.sleep(Xd),O(await o.startUnlocked(d,void 0,!1))}async function Le(o,n){let a=K1();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 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-acceptance-session requires the admitted daemon generation to be running.");let c=we(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:Ir(s)},S=await o.waitForStop(s.pid,lT,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(Xd),O(await o.startUnlocked({...Yo(s.options),strictPort:!0},void 0,!1))}async function xt(o,n,a,{generation:s,scope:c,startupSecret:d}){let u=await n.callDaemonMethod(W1,{...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(z1,{...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(j1,{...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 te{host;constructor(o){this.host=o}async recoverControlState(o,n,a,s){if(this.host.throwIfRecoveryCancelled(a),!this.host.acquireLock())return O(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(Xd),this.host.throwIfRecoveryCancelled(a),O(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(Ir(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":Ba(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=Ba(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=Yo(Object.fromEntries(Object.entries(n).filter(([,c])=>c!==void 0&&c!==!1)));return x(Yo(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 zt}from"fs/promises";import{existsSync as Ie}from"fs";import{mkdirSync as jt}from"fs";import{dirname as Kt}from"path";class EG{incumbent=null;supersededOwner=null;contenderEarlyOwner=null;sawLiveContender=!1;deps;constructor(o){this.deps={readPidFile:o?.readPidFile??(()=>So()),persistPidFile:o?.persistPidFile??qt,isProcessRunning:o?.isProcessRunning??((n)=>nt(n,{debugLog:e.debug})),readProcessGenerationToken:o?.readProcessGenerationToken??la,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&&Fe(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=Vt(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:Te(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)&&!pw(o.pid,o,this.deps.readProcessGenerationToken,"the daemon PID record")}}function Vt(o){return{pid:o.pid,...ad(Ir(o))}}function Te(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,...ad(Ir(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 Fe(o){return o.entryScript!==void 0&&o.buildId!==void 0}function Ce(o){return Fe(o)||Te(o.supersededOwner)!==null}function qt(o){jt(Kt(vr),{recursive:!0}),hee(vr,o)}class N extends Error{}class re{host;constructor(o){this.host=o}async stop(o=Xi,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(),E(this.host.socketPath,this.host.seams.exitRecordFileSystem),h("Daemon is not running");return}await this.host.stopRunningDaemon(a,o),E(this.host.socketPath,this.host.seams.exitRecordFileSystem)}async stopRunningDaemon(o,n=Xi,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,lT,c),m||=d.replacedByOtherGeneration,!d.stopped)throw new t(`Daemon process ${s} did not exit after SIGKILL`)}if(!m)await pv({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:Ir(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 pv({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(!Ie(this.host.pidFilePath))return;try{let o=await zt(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()&&Ce(o)}async removeConfirmedDeadPidFile(){let o=await this.readConfirmedDeadPidData();if(!o||this.mustKeepDeadRecordAsSocketOwnerProof(o))return;let n=this.host.timer.now()+Yt,a=this.host.acquireLock();while(!a&&this.host.remainingTime(n)>0)await this.host.timer.sleep(Math.min(Xt,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 pv({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??Vc,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(Xi,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(lT,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,Xi,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,lT,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(Em))return!1;return this.host.matchesObservedDaemonGeneration(n,{pid:o.pid,ppid:0,command:"",startedAt:o.processStartedAt??o.startedAt,processGenerationToken:Ir(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:Ir(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&&pw(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(!Ie(this.host.pidFilePath))return null;try{let o=vt("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 Yt=2000,Xt=50;var oe=f({running:ee(!0),pid:A().int().positive(),startedAt:A().positive(),processStartedAt:A().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:kt(y(),y().min(1))}),G=f({accepted:Z(),reason:y().optional()}),Qt=oe.omit({running:!0,reportedPidFilePath:!0,reportedSocketPath:!0,reportedSockets:!0}).extend({port:A().int().positive(),dbPath:y().min(1),daemonSessionId:y().min(1),launchLogPath:y().nullable(),options:LI,sockets:kt(y(),y().min(1))});function H(o,n){let a=Qt.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 lX(o,n,a,s){if(!o)return!1;let c=a.readRecord();if(H(c,s)&&c.pid===n.pid&&c.startedAt===n.startedAt&&Ir(c)===n.processGenerationToken)return!0;if(c&&c.pid!==n.pid&&a.isProcessRunning(c.pid))return!1;return await a.writeRecord(),!0}class ne{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 oe.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 _r?"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 _r(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($1,{...o});return G.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 H(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)||!H(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 Zt=3000;class ae{host;constructor(o){this.host=o}async restart(o={},n){return Oe(this.restartHost(),o,n)}async restartAdmitted(o,n){return Ee(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 Le(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 pv({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(U1,{pid:o.pid,startedAt:o.startedAt,...ad(Ir(o)),version:o.version,buildId:o.buildId,entryScript:o.entryScript},{timeoutMs:Zt});if(!a||typeof a!=="object")throw new _r("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 _r("the daemon returned an unrecognized safe-restart admission result")}catch(a){if(a instanceof _r)throw a;throw new _r(`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 _r("incumbent database path or startup options unavailable");let n=this.host.createClient({clientIdentity:null}),a;try{let s=await n.callDaemonMethod(H1,{...o}),c=G.passthrough().parse(s);if(!c.accepted||typeof c.maintenanceToken!=="string")throw new _r(c.reason??"maintenance admission unavailable",c.reason);a=c.maintenanceToken;let d=await this.host.admitMaintenanceRestart(o,a);if(!d.accepted)throw new _r(d.reason??"maintenance admission refused",d.reason);return{accepted:!0}}finally{if(a)try{await n.callDaemonMethod(q1,{...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(V1,{pid:o.pid,startedAt:o.startedAt,...ad(Ir(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&&tr(c.reason))return{accepted:!1,reason:c.reason};return{accepted:!1,reason:"maintenance_token_invalid"}}catch(s){throw new _r(`maintenance admission is unavailable: ${r(s)}`)}finally{await a.close()}}}var er=new Set(["active_operations","active_sessions","generation_changed","maintenance_token_invalid","maintenance_token_consumed","restart_pending","shutdown_unavailable","sessions_unavailable"]);function tr(o){return typeof o==="string"&&er.has(o)}class ku{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:cr,exitRecordFileSystem:DP,launchLogFileSystem:{openSync:nr,closeSync:ar},launchWorkingDirectory:g$,currentBuildId:()=>No().buildId,nextLaunchNonce:()=>L.next()};startupLockOwnerToken;platform;lockOwnerGenerationProbe;constructor(o={}){let n=dr(o);this.lockOwnerGenerationProbe=n.lockOwnerGenerationProbe,this.identityRecoveryIO=n.identityRecoveryIO??{socketExists:()=>this.platform!=="win32"&&or(this.socketPath),readRecord:()=>So(this.pidFilePath),probe:()=>this.platform==="win32"?Promise.reject(Error("Failed to connect to daemon: socket-owner probing is unsupported on win32")):new ya(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 Cw({timer:n.timer}),this.stateProvider=n.stateProvider,this.timer=n.timer,this.lockFilePath=Ae(n.lockFilePath),this.pidFilePath=Ae(n.pidFilePath),this.socketPath=Ae(n.socketPath),this.processFinder=n.processFinder,this.processLivenessChecker=sr(n.processFinder)?n.processFinder:FC(),this.processSignaler=n.processSignaler,this.extractionCleaner=n.extractionCleaner,this.launchCommandResolver=n.launchCommandResolver,this.launcher=n.launcher??new kW({spawn:n.processSpawner?.spawn.bind(n.processSpawner),timer:n.timer}),this.fallbackLauncher=new kW({entryScript:null,spawn:n.processSpawner?.spawn.bind(n.processSpawner),timer:n.timer}),this.clientFactory=n.clientFactory??((a)=>new ya(this.socketPath,void 0,n.timer,{recoveryOptions:{},clientIdentity:a?.clientIdentity})),this.daemonProtocolHealthProbe=n.daemonProtocolHealthProbe??(async()=>{try{return await new ya(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=Xi,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=Xi,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 K(o),daemonControlRecovery:new te(o),daemonShutdown:new re(o),daemonIdentityRecovery:new ne(o),daemonRestartCoordinator:new ae(o),daemonReadiness:new V(o)}}collaboratorHost(){let o=this,n;return{...this.collaboratorOperations(),get takeoverDeferrals(){return n??=new z(new sC(`${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 ir={signal(o,n){process.kill(o,n)}};function sr(o){return typeof o?.isProcessRunning==="function"}function cr(o){return new Promise((n)=>{let a=rr();a.once("error",()=>n(!1)),a.listen(o,()=>a.close(()=>n(!0)))})}async function Aoe(o,n,a={}){return BG(o,n,a,ku)}function dr(o){let n=mr(o),{extractionCleaner:a=le,processSignaler:s=ir,idGenerator:c=L,platform:d=process.platform,portAvailabilityChecker:m=new jL,retryExecutor:u=new hn(n.timer),lockOwnerGenerationProbe:p=Nt}=o;return{...o,...n,extractionCleaner:a,processSignaler:s,idGenerator:c,platform:d,portAvailabilityChecker:m,retryExecutor:u,lockOwnerGenerationProbe:p}}function mr(o){let{stateProvider:n=()=>QF(w),timer:a=i,lockFilePath:s=LV,pidFilePath:c=vr,socketPath:d=Ct,processFinder:m=FC()}=o;return{stateProvider:n,timer:a,lockFilePath:s,pidFilePath:c,socketPath:d,processFinder:m}}export{$1,U1,H1,q1,V1,W1,z1,j1,_r,YE,DP,cX,AG,Yo,TG,kG,dX,K1,EG,lX,ku,Aoe};
8
+
9
+ //# debugId=0733DF49A373DDA064756E2164756E21
@@ -0,0 +1,5 @@
1
+ // @bun
2
+ import{K,E}from"./chunk-mf9spd4g.js";import{Pl}from"./chunk-2v7tw1nj.js";import*as c from"fs";import*as l from"os";import*as n from"path";function e5(o={}){let t={env:o.env??process.env,platform:o.platform??process.platform,homedir:o.homedir??l.homedir,directoryExists:o.directoryExists??b};f(t),m(t)}function f(o){let{env:t,directoryExists:e}=o,r=n.delimiter,i=t.PATH??"",s=new Set(i.split(r).filter(Boolean)),u=h(o),a=[];for(let d of u)if(!s.has(d)&&e(d))a.push(d),s.add(d);if(a.length===0)return;t.PATH=i.length>0?`${i}${r}${a.join(r)}`:a.join(r)}function m(o){let{env:t,directoryExists:e}=o;if(t.ANDROID_HOME||t.ANDROID_SDK_ROOT)return;for(let r of A(o))if(e(r)){t.ANDROID_HOME=r;return}}function h({env:o,platform:t,homedir:e}){let r=e();if(t==="darwin")return["/usr/bin","/bin","/usr/sbin","/sbin","/usr/local/bin","/usr/local/sbin","/opt/homebrew/bin","/opt/homebrew/sbin",n.join(r,"Library/Android/sdk/platform-tools"),n.join(r,"Library/Android/sdk/emulator"),n.join(r,"Library/Android/sdk/cmdline-tools/latest/bin")];if(t==="linux")return["/usr/bin","/bin","/usr/sbin","/sbin","/usr/local/bin","/usr/local/sbin",n.join(r,"Android/Sdk/platform-tools"),n.join(r,"Android/Sdk/emulator"),n.join(r,"Android/Sdk/cmdline-tools/latest/bin")];if(t==="win32"){let i=E(K.LOCALAPPDATA,o),s=i?n.join(i,"Android","Sdk"):"";return[...s?[n.join(s,"platform-tools"),n.join(s,"emulator"),n.join(s,"cmdline-tools","latest","bin")]:[]]}return[]}function A({env:o,platform:t,homedir:e}){let r=e();if(t==="darwin")return[n.join(r,"Library/Android/sdk")];if(t==="linux")return[n.join(r,"Android/Sdk")];if(t==="win32"){let i=E(K.LOCALAPPDATA,o);return i?[n.join(i,"Android","Sdk")]:[]}return[]}function b(o){return Pl(()=>c.statSync(o).isDirectory(),()=>!1)}var p=async()=>{};function MQ(o){let t=p;return p=o,()=>{p=t}}function KF(o){return p(o)}
3
+ export{e5,MQ,KF};
4
+
5
+ //# debugId=E9E7C3A2D3AFBBA964756E2164756E21
@@ -0,0 +1,5 @@
1
+ // @bun
2
+ import{Ar,lt,it,ue,he,Pq,O7,mh}from"./chunk-tyazf3sk.js";import{g,$e,soe}from"./chunk-mf9spd4g.js";import{i,e}from"./chunk-z8t0v07j.js";import{Cr,M}from"./chunk-h3n4adc6.js";import{xb,zi}from"./chunk-3jmvqygr.js";import{sS}from"./chunk-nwm2pq5v.js";import{BZ,Ey,C6,Iy,D6,Hf,UN,FI,UZ}from"./chunk-8cghfzb2.js";import{n,a,Oe,b,s,IR,Me,I}from"./chunk-79q5xsdc.js";import{r,t}from"./chunk-9rkfyt6q.js";var H="Invalid tools/call request: ",X="Invalid tools/call result: ",Z="AutoMobile drives Android and iOS devices. Start with listDevices, getAndroid or getApple, then bind your session. Call observe before acting and again after each action; element ids are only valid for the observation that returned them. Prefer tapOn/sendKeys on observed elements over raw coordinates. Large artifacts (screenshots, logs) are resources, not inline output. Read the automobile usage skill (skill://auto-mobile-usage/SKILL.md) for the full workflow before your first device call.";function ee(o=process.env){return $e(g.SERVER_INSTRUCTIONS,o)?Z:void 0}function uO(o,c,l={}){let{cacheHints:d,requestState:u,instructions:m=ee()}=l,p=new mh(o,{capabilities:{...c,prompts:void 0},...d&&{cacheHints:d},...u&&{requestState:u},...m!==void 0&&{instructions:m}});if(c.prompts)p.server.registerCapabilities({prompts:c.prompts});return te(p.server),p}class q{result;constructor(o){this.result=o}}function te(o){let c=o._wrapHandler.bind(o);o._wrapHandler=(l,d)=>{if(l!=="tools/call")return c(l,(m,p)=>d(m,L(p)));let u=c(l,async(m,p)=>{let f=await d(m,L(p));if(Hf(f))throw new q(f);return f});return async(m,p)=>{try{return await u(m,p)}catch(f){if(f instanceof q)return f.result;throw re(f)}}}}function re(o){if(!(o instanceof he)||o instanceof zi||o.code!==ue.InvalidParams)return o;if(o.message.startsWith(H))return new he(xb.InternalError,o.message.slice(H.length),o.data);if(o.message.startsWith(X))return new zi(xb.InvalidParams,o.message,o.data);return o}function L(o){return{...o,mcpReq:{...o.mcpReq,signal:oe(o.mcpReq.signal)}}}function oe(o){let c=new AbortController,l=()=>{c.abort(ne(o.reason)?void 0:o.reason)};if(o.aborted)l();else o.addEventListener("abort",l,{once:!0});return c.signal}function ne(o){return o instanceof it&&o.code===lt.ConnectionClosed}var D="x-auto-mobile-mcp-session-id";function x$(o){let c=o["x-auto-mobile-mcp-session-id"],l=Array.isArray(c)?c[0]:c;return typeof l==="string"&&l.length>0?l:void 0}var w=s({version:I(1),toolName:n(),argumentsHash:n(),deviceIds:b(n())}),ie={createSecret:()=>crypto.getRandomValues(new Uint8Array(32))},z=600000,ae=w.extend({expiresAt:a().finite()});function se(o){let c=x$({[D]:o.http?.req?.headers.get(D)??void 0});return JSON.stringify(["ambiguous-device",c??null])}function ce(o={}){let c=o.timer??i,l,d=()=>(l??=BZ({key:(o.secretProvider??ie).createSecret(),ttlSeconds:z/1000,bind:se}),l);return{mint:(u,m)=>d().mint({...u,expiresAt:c.now()+z},m),verify:async(u,m)=>{let p=ae.parse(await d().verify(u,m));if(c.now()>=p.expiresAt)throw Error("expired");return w.parse(p)}}}var C$=ce();import{createHash as Ee}from"crypto";function Kk(o=process.env){return soe(g.ELICITATION,o)!=="off"}class T{declined=new Set;static key(o){return[...new Set(o)].sort().join("\x00")}remembers(o){return this.declined.has(T.key(o))}remember(o){this.declined.add(T.key(o))}}function j(o){return typeof o==="object"&&o!==null&&!Array.isArray(o)}function GR(o){let c=j(o)?o.elicitation:void 0;if(!j(c))return"none";if(c.form!==void 0)return"form";return c.url!==void 0?"url":"bare"}function le(o){return`[elicitation] ${o.toolName} era=${o.era} declared=${o.declared} outcome=${o.outcome} candidates=${o.candidateCount}`+(o.latencyMs===void 0?"":` latencyMs=${o.latencyMs}`)}var B={record:(o)=>e.info(le(o))};function JY(o){return{record(c){B.record(c),o.recordElicitationEvent(c)}}}var K=B;function XY(o){K=o}var Gk={record:(o)=>K.record(o)};var de=20000;function U(o){return typeof o==="object"&&o!==null&&!Array.isArray(o)}function pO(o){let c=U(o)?o.elicitation:void 0;if(!U(c))return!1;return c.form!==void 0||c.url===void 0}function V(o,c){return{declaresElicitation:()=>c.mcpReq.envelope===void 0&&pO(o.server.getClientCapabilities()),declaration:()=>c.mcpReq.envelope===void 0?GR(o.server.getClientCapabilities()):"none",elicit:(l,d)=>o.server.request({method:"elicitation/create",params:l},{signal:d})}}var me=s({isError:I(!0),content:b(IR({type:n()})).min(1)}),pe=s({code:I(sS),candidates:b(s({deviceId:n(),platform:n().default("unknown")}))}),fe=s({type:I("text"),text:n()});function ve(o){let c=me.safeParse(o),l=c.success?fe.safeParse(c.data.content[0]):void 0;if(!l?.success||!l.data.text.includes(sS))return;try{let d=pe.safeParse(JSON.parse(l.data.text));return d.success?d.data:void 0}catch(d){e.debug(`ambiguous device result is not JSON: ${r(d)}`);return}}function h(o){let c=new Map((ve(o)?.candidates??[]).map((l)=>[l.deviceId,l]));return c.size>1?[...c.values()]:void 0}function P(o,c){return{mode:"form",message:`${o} matched ${c.length} devices. Which device should it use?`,requestedSchema:{type:"object",properties:{deviceId:{type:"string",title:"Device",description:"The device this call should run on.",oneOf:c.map(({deviceId:l,platform:d})=>({const:l,title:`${l} (${d})`}))}},required:["deviceId"]}}}function ge(o,c){if(o.action!=="accept")return;let l=o.content?.deviceId;return typeof l==="string"&&c.some(({deviceId:d})=>d===l)?l:void 0}function ye(o,c){if(o.action!=="accept")return{outcome:o.action};let l=ge(o,c);return l===void 0?{outcome:"invalid"}:{outcome:"accept",deviceId:l}}async function Re(o,c,l,d){let u=new AbortController,m=!1,p=()=>u.abort();d.callSignal.addEventListener("abort",p,{once:!0});let f=d.timer.setTimeout(()=>{m=!0,p()},d.timeoutMs);try{let v=await o.elicit(P(c,l),u.signal);return ye(v,l)}catch(v){if(u.signal.aborted)return e.debug(`device choice for ${c} not answered: ${r(v)}`),{outcome:m?"timeout":"cancel"};return e.warn(`device choice elicitation for ${c} failed: ${r(v)}`,v),{outcome:"error"}}finally{d.timer.clearTimeout(f),d.callSignal.removeEventListener("abort",p)}}function F(o,c,l={}){let d=l.timer??i,u=l.timeoutMs??de,m=l.recorder??Gk,p=()=>c.declaration?.()??(c.declaresElicitation()?"form":"none"),f=l.enabled??(()=>Kk()),v=(R,C,E)=>m.record({toolName:R.name,era:"legacy",declared:p(),outcome:E,candidateCount:C,atMs:d.now()}),y=(R)=>{if(!f())return"disabled";if(!c.declaresElicitation())return"not_offered";return l.declines?.remembers(R)?"remembered":void 0};return{...o,execute:async(R)=>{let C=await o.execute(R),E=R.args.deviceId===void 0?h(C):void 0;if(!E)return C;let S=E.map(({deviceId:Y})=>Y),_=y(S);if(_)return v(R,E.length,_),C;let Q=d.now(),x=await Re(c,R.name,E,{timer:d,timeoutMs:u,callSignal:R.extra.signal}),N=d.now();if(m.record({toolName:R.name,era:"legacy",declared:p(),outcome:x.outcome,candidateCount:E.length,atMs:N,latencyMs:N-Q}),x.outcome==="decline"||x.outcome==="cancel")l.declines?.remember(S);return x.deviceId===void 0?C:o.execute({...R,args:{...R.args,deviceId:x.deviceId}})}}}async function D$(o,c,l,d){let u=await c(o),m=h(u);if(!m)return u;let p=d?.timer??i,f=p.now(),v=(C,E)=>{let S=p.now();d?.recorder.record({toolName:o.name,era:"modern",declared:d.declared,outcome:C,candidateCount:m.length,atMs:S,...E?{latencyMs:S-f}:{}})},y=await l({candidates:m,inputRequests:{deviceChoice:Pq.elicit(P(o.name,m))}});if(!y)return v("not_offered",!1),u;if("pending"in y)return v("asked",!1),y.pending;let R=O7(y.responses,"deviceChoice",s({deviceId:n().refine((C)=>m.some(({deviceId:E})=>E===C)&&(y.offeredDeviceIds===void 0||y.offeredDeviceIds.includes(C)))}));return v(R?"accept":Ce(y.responses),!0),R?c({...o,args:{...o.args,deviceId:R.deviceId}}):u}function Ce(o){let c=o.deviceChoice,l=typeof c==="object"&&c!==null&&"action"in c?c.action:void 0;return l==="decline"||l==="cancel"?l:"invalid"}function W(o,c=Gk,l=()=>Kk()){return{...o,execute:async(d)=>{let u=!l();if(d.args.deviceId!==void 0||u||!pO(d.extra.envelope?.[Ar])){let f=await o.execute(d),v=d.args.deviceId===void 0&&h(f);if(v)Se(c,d,v.length,u?"disabled":"not_offered");return f}let m={...d.args};delete m.deviceId;let p=Ee("sha256").update(Cr(m)).digest("hex");return D$(d,(f)=>o.execute(f),async({candidates:f,inputRequests:v})=>{if(d.extra.inputResponses!==void 0){let y=w.safeParse(d.extra.deviceChoiceState?.verified);if(!y.success||y.data.toolName!==d.name||y.data.argumentsHash!==p)return;return{responses:d.extra.inputResponses,offeredDeviceIds:y.data.deviceIds}}if(!d.extra.deviceChoiceState)return;return{pending:Pq({requestState:await d.extra.deviceChoiceState.mint({version:1,toolName:d.name,argumentsHash:p,deviceIds:f.map(({deviceId:y})=>y)}),inputRequests:v})}},{recorder:c,declared:GR(d.extra.envelope?.[Ar])})}}}function Se(o,c,l,d){o.record({toolName:c.name,era:"modern",declared:GR(c.extra.envelope?.[Ar]),outcome:d,candidateCount:l,atMs:i.now()})}function xe(o,c){let l=o._meta?.progressToken;if(l===void 0)return;return async(d,u,m)=>{try{await o.sendNotification({method:"notifications/progress",params:{progressToken:l,progress:d,total:u,...m&&{message:m}}})}catch(p){e.warn(`${c}: ${p}`)}}}async function Te(o,c,l){l.prepare?.(o);let d=o.params.name,u=o.params.arguments||{};if(!d)throw new t("Tool name is missing in the request");return l.execute({name:d,args:u,progressToken:c._meta?.progressToken,progress:xe(c,l.progressFailureMessage),extra:c})}function be(o,c){return{signal:o.mcpReq.signal,_meta:o.mcpReq._meta,...o.mcpReq.envelope!==void 0&&{envelope:o.mcpReq.envelope},...o.mcpReq.inputResponses!==void 0&&{inputResponses:o.mcpReq.inputResponses},...c&&{deviceChoiceState:{verified:o.mcpReq.requestState(),mint:(l)=>c.mint(l,o)}},sendNotification:(l)=>o.mcpReq.notify(l)}}function mO(o,c,l={}){let d=new T,u=l.era==="modern"?W(c):c,m=l.era==="modern"?l.deviceChoiceRequestState??C$:void 0;o.server.setRequestHandler("tools/call",async(p,f)=>await Te(p,be(f,m),l.era!=="modern"&&l.ambiguousDeviceElicitation?F(c,V(o,f),{declines:d,...l.ambiguousDeviceElicitation}):u))}function mb(o,c=M.isToolResultsNoStructuredContentEnabled()){if(!o)return"no-schema";if(c)return"flag";return null}function I2(o){return o!==null&&typeof o==="object"&&"structuredContent"in o}function fb(o,c){if(c!==null&&I2(o))delete o.structuredContent;return o}var J=IR({taskId:n()}),we=IR({taskId:n(),inputResponses:Me(n(),Oe()).optional()});function _2(o){let c=o._oninitialize.bind(o);o.setRequestHandler("initialize",async(l,d)=>{let u=await c(l);if(!(D6(l.params.capabilities)||G(d)))return u;return{...u,capabilities:{...u.capabilities,extensions:{...u.capabilities.extensions,[Ey]:{}}}}})}function G(o){return Iy({envelope:o.mcpReq.envelope,meta:o.mcpReq._meta})}function A(o){if(!G(o))throw UN()}function O(o){if(!o.ownerKey)throw FI("not_found");return o.ownerKey}function ZY(o,c){let l=o.server;_2(l),l.setRequestHandler("tasks/get",{params:J},async(d,u)=>{A(u);let m=await c.taskManager.get(O(c),d.taskId);return UZ(m)}),l.setRequestHandler("tasks/update",{params:we},async(d,u)=>{A(u);let m=u.mcpReq.inputResponses??d.inputResponses??{};return await c.taskManager.update(O(c),d.taskId,m),C6}),l.setRequestHandler("tasks/cancel",{params:J},async(d,u)=>(A(u),await c.taskManager.cancel(O(c),d.taskId),C6))}
3
+ export{uO,x$,C$,Kk,GR,JY,XY,Gk,pO,D$,mO,mb,I2,fb,_2,ZY};
4
+
5
+ //# debugId=CC4AE4B8FC0FE08864756E2164756E21
@@ -0,0 +1,4 @@
1
+ // @bun
2
+ import{e5}from"./chunk-zg67wjkh.js";import"./chunk-mf9spd4g.js";export{e5 as bootstrapEnvironment};
3
+
4
+ //# debugId=F3D46A386040206464756E2164756E21
@@ -0,0 +1,4 @@
1
+ // @bun
2
+ import{yS,n0,nc}from"./chunk-vefd8qee.js";import"./chunk-sjn0nj4p.js";import"./chunk-4xd6zs3y.js";import"./chunk-pm06b05d.js";import"./chunk-bn64x5z5.js";import"./chunk-0e4gm1kj.js";import"./chunk-4fgdhcwx.js";import"./chunk-6d3mmqxt.js";import"./chunk-sns0c35v.js";import"./chunk-h3n4adc6.js";import"./chunk-32jpxz2y.js";import"./chunk-79q5xsdc.js";import"./chunk-ggtd5x5a.js";import"./chunk-z8t0v07j.js";import"./chunk-mf9spd4g.js";export{nc as TapOnElement,yS as tapFocusFailure,n0 as tapResolvedLayer};
3
+
4
+ //# debugId=A279C9E44CB8784464756E2164756E21
@@ -0,0 +1,4 @@
1
+ // @bun
2
+ import{EV}from"../chunk-f8tnk179.js";export{EV as PROCESS_ENTRY_PARENT_PID};
3
+
4
+ //# debugId=07BB018530514F3D64756E2164756E21