@bastani/atomic 0.10.4 → 0.10.5-alpha.1

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 (537) hide show
  1. package/CHANGELOG.md +44 -0
  2. package/dist/_shared/compile-cache-warmup-host-RU5L7I7A.js +1 -1
  3. package/dist/_shared/dist-KOELCESV.js +48 -3
  4. package/dist/_shared/fork-row-index-UAUAQRD5.js +47 -2
  5. package/dist/_shared/http-YFAPTIZD.js +16 -4
  6. package/dist/_shared/http-YFAPTIZD.js.map +1 -1
  7. package/dist/_shared/lib-4PES5P4V.js +59 -14
  8. package/dist/_shared/mode-interactive-sdk-7KXUFI2F.js +1706 -258
  9. package/dist/_shared/mode-interactive-sdk-7KXUFI2F.js.map +1 -1
  10. package/dist/_shared/mode-rpc-sdk-IOPGDYR4.js +317 -64
  11. package/dist/_shared/mode-rpc-sdk-IOPGDYR4.js.map +1 -1
  12. package/dist/_shared/{mode-shared-HP7GUA7J.js → mode-shared-2QJSCUM6.js} +432 -81
  13. package/dist/_shared/mode-shared-2QJSCUM6.js.map +1 -0
  14. package/dist/_shared/p0-cli-BB45ZQY6.js +3482 -0
  15. package/dist/_shared/p0-cli-BB45ZQY6.js.map +1 -0
  16. package/dist/_shared/p0-cli-GUFK7TPN.js +2 -2838
  17. package/dist/_shared/p0-cli-GUFK7TPN.js.map +1 -1
  18. package/dist/_shared/{p1a-prewarm-YK3KDTLN.js → p1a-prewarm-UQY3X2UK.js} +270 -73
  19. package/dist/_shared/p1a-prewarm-UQY3X2UK.js.map +1 -0
  20. package/dist/_shared/{p1b-elig-PXQA2FYP.js → p1b-elig-ENCUPKKJ.js} +190 -121
  21. package/dist/_shared/p1b-elig-ENCUPKKJ.js.map +1 -0
  22. package/dist/_shared/p2-common-YLSYXMDQ.js +1 -3
  23. package/dist/_shared/p2-common-YLSYXMDQ.js.map +1 -1
  24. package/dist/_shared/p2-shell-TJBYQMCJ.js +1 -1
  25. package/dist/_shared/p2-shell-main-B2WIALFD.js +500 -127
  26. package/dist/_shared/p2-shell-main-B2WIALFD.js.map +1 -1
  27. package/dist/_shared/runtime-O4KCSG4C.js +4 -4
  28. package/dist/_shared/sdk-WQIOHVKO.js +56 -11
  29. package/dist/_shared/session-data-AHTU7IS6.js +48 -3
  30. package/dist/_shared/session-manager-list-2BLEEZVG.js +2 -2
  31. package/dist/_shared/settings-startup-65YEWRV2.js.map +1 -1
  32. package/dist/_shared/sql-session-store-5FD3WBMZ.js +57 -12
  33. package/dist/_shared/{startup-0-0-X4NF3GKM.js → startup-0-0-TYUFUOJZ.js} +519 -316
  34. package/dist/_shared/startup-0-0-TYUFUOJZ.js.map +1 -0
  35. package/dist/_shared/{startup-0-1-7QTG6VJZ.js → startup-0-1-D4LGGINF.js} +284 -81
  36. package/dist/_shared/startup-0-1-D4LGGINF.js.map +1 -0
  37. package/dist/_shared/{startup-0-2-KFDYPDJK.js → startup-0-2-SZGQIWHI.js} +483 -154
  38. package/dist/_shared/startup-0-2-SZGQIWHI.js.map +1 -0
  39. package/dist/_shared/startup-0-3-T4DVFYWX.js +340 -110
  40. package/dist/_shared/startup-0-3-T4DVFYWX.js.map +1 -1
  41. package/dist/_shared/startup-0-4-HN5EB4K7.js +261 -59
  42. package/dist/_shared/startup-0-4-HN5EB4K7.js.map +1 -1
  43. package/dist/_shared/startup-0-5-OHJNE6JH.js +421 -148
  44. package/dist/_shared/startup-0-5-OHJNE6JH.js.map +1 -1
  45. package/dist/_shared/startup-10-0-TDQNBDDL.js +62 -11
  46. package/dist/_shared/startup-10-0-TDQNBDDL.js.map +1 -1
  47. package/dist/_shared/startup-12-0-55AAXBJZ.js +3 -3
  48. package/dist/_shared/startup-14-0-MLX36RBG.js +12 -11
  49. package/dist/_shared/startup-14-0-MLX36RBG.js.map +1 -1
  50. package/dist/_shared/startup-15-0-YUKGAC63.js +53 -158
  51. package/dist/_shared/startup-15-0-YUKGAC63.js.map +1 -1
  52. package/dist/_shared/startup-15-1-4S7FLMNG.js +231 -46
  53. package/dist/_shared/startup-15-1-4S7FLMNG.js.map +1 -1
  54. package/dist/_shared/startup-8-0-34CBHPZH.js +115 -35
  55. package/dist/_shared/startup-8-0-34CBHPZH.js.map +1 -1
  56. package/dist/_shared/{startup-8-1-KQJBDKRU.js → startup-8-1-SJW2GMAM.js} +203 -62
  57. package/dist/_shared/startup-8-1-SJW2GMAM.js.map +1 -0
  58. package/dist/_shared/storage-command-7MGXLJGZ.js +55 -10
  59. package/dist/_shared/task-unsaved-answer-VJ2KTB4V.js +47 -2
  60. package/dist/_shared/tree-outline-MUEPK5B7.js +48 -3
  61. package/dist/builtin/intercom/CHANGELOG.md +21 -0
  62. package/dist/builtin/intercom/README.md +0 -1
  63. package/dist/builtin/intercom/broker/broker-instance.ts +13 -57
  64. package/dist/builtin/intercom/broker/broker-process.ts +30 -10
  65. package/dist/builtin/intercom/broker/broker-routing.ts +12 -2
  66. package/dist/builtin/intercom/broker/broker.bundle.mjs +2557 -498
  67. package/dist/builtin/intercom/broker/broker.ts +164 -55
  68. package/dist/builtin/intercom/broker/client.ts +36 -16
  69. package/dist/builtin/intercom/broker/control.ts +83 -20
  70. package/dist/builtin/intercom/broker/durable-ended-queue.ts +65 -19
  71. package/dist/builtin/intercom/broker/host-command-environment.ts +7 -2
  72. package/dist/builtin/intercom/broker/multinode-router.ts +1675 -387
  73. package/dist/builtin/intercom/broker/multinode-state-store.ts +10 -0
  74. package/dist/builtin/intercom/broker/paths.ts +68 -6
  75. package/dist/builtin/intercom/broker/pending-send-registry.ts +5 -0
  76. package/dist/builtin/intercom/broker/registration-bounds.ts +38 -0
  77. package/dist/builtin/intercom/broker/retiring-broker-check.ts +178 -0
  78. package/dist/builtin/intercom/broker/return-paths.ts +268 -7
  79. package/dist/builtin/intercom/broker/send-handler.ts +253 -28
  80. package/dist/builtin/intercom/broker/send-order-gate.ts +410 -0
  81. package/dist/builtin/intercom/broker/spawn.ts +950 -202
  82. package/dist/builtin/intercom/broker/sql-lease-store.ts +37 -0
  83. package/dist/builtin/intercom/broker/sql-outbox-store.ts +7 -0
  84. package/dist/builtin/intercom/broker/windows-cwd.ts +546 -0
  85. package/dist/builtin/intercom/index.bundle.mjs +3506 -2328
  86. package/dist/builtin/intercom/package.json +1 -1
  87. package/dist/builtin/intercom/retry-policy.ts +4 -0
  88. package/dist/builtin/intercom/types.ts +2 -0
  89. package/dist/builtin/mcp/index.bundle.mjs +1 -1
  90. package/dist/builtin/mcp/package.json +1 -1
  91. package/dist/builtin/subagents/CHANGELOG.md +6 -0
  92. package/dist/builtin/subagents/package.json +1 -1
  93. package/dist/builtin/subagents/src/extension/index.bundle.mjs +336 -86
  94. package/dist/builtin/web-access/index.bundle.mjs +23 -38
  95. package/dist/builtin/web-access/package.json +1 -1
  96. package/dist/bun/cli.js +1 -1
  97. package/dist/bun/cli.js.map +1 -1
  98. package/dist/bun/internal-intercom-broker.js +119 -4
  99. package/dist/bun/internal-intercom-broker.js.map +1 -1
  100. package/dist/bun/register-theme-validator.js +6 -0
  101. package/dist/bun/register-theme-validator.js.map +1 -0
  102. package/dist/cli/args.js +2 -2
  103. package/dist/cli/auth-cli.code.js +1102 -0
  104. package/dist/cli/auth-cli.code.js.map +1 -0
  105. package/dist/cli/auth-cli.impl.js +30 -1096
  106. package/dist/cli/auth-cli.impl.js.map +1 -1
  107. package/dist/cli/auth-cli.js +11 -7
  108. package/dist/cli/blueprint-command.code.js +906 -0
  109. package/dist/cli/blueprint-command.code.js.map +1 -0
  110. package/dist/cli/blueprint-command.impl.js +30 -900
  111. package/dist/cli/blueprint-command.impl.js.map +1 -1
  112. package/dist/cli/blueprint-command.js +11 -7
  113. package/dist/cli/intercom-command.code.js +153 -0
  114. package/dist/cli/intercom-command.code.js.map +1 -0
  115. package/dist/cli/intercom-command.impl.js +33 -105
  116. package/dist/cli/intercom-command.impl.js.map +1 -1
  117. package/dist/cli/intercom-command.js +11 -7
  118. package/dist/cli/list-models.code.js +60 -0
  119. package/dist/cli/list-models.code.js.map +1 -0
  120. package/dist/cli/list-models.impl.js +33 -57
  121. package/dist/cli/list-models.impl.js.map +1 -1
  122. package/dist/cli/list-models.js +11 -7
  123. package/dist/cli/session-picker.code.js +55 -0
  124. package/dist/cli/session-picker.code.js.map +1 -0
  125. package/dist/cli/session-picker.impl.js +33 -52
  126. package/dist/cli/session-picker.impl.js.map +1 -1
  127. package/dist/cli/session-picker.js +11 -7
  128. package/dist/cli/startup-ui.code.js +5 -0
  129. package/dist/cli/startup-ui.code.js.map +1 -0
  130. package/dist/cli/startup-ui.impl.js +35 -4
  131. package/dist/cli/startup-ui.js +11 -7
  132. package/dist/cli/storage-command.code.js +3 -0
  133. package/dist/cli/storage-command.code.js.map +1 -0
  134. package/dist/cli/storage-command.impl.js +35 -2
  135. package/dist/cli/storage-command.js +11 -7
  136. package/dist/cli/storage-search-session.code.js +189 -0
  137. package/dist/cli/storage-search-session.code.js.map +1 -0
  138. package/dist/cli/storage-search-session.impl.js +33 -186
  139. package/dist/cli/storage-search-session.impl.js.map +1 -1
  140. package/dist/cli/storage-search-session.js +11 -7
  141. package/dist/cli/team-command.code.js +217 -0
  142. package/dist/cli/team-command.code.js.map +1 -0
  143. package/dist/cli/team-command.impl.js +32 -213
  144. package/dist/cli/team-command.impl.js.map +1 -1
  145. package/dist/cli/team-command.js +11 -7
  146. package/dist/cli.js +60 -11
  147. package/dist/cli.js.map +1 -1
  148. package/dist/config.js +1 -1
  149. package/dist/core/agent-session-methods.d.ts +4 -3
  150. package/dist/core/agent-session-methods.js.map +1 -1
  151. package/dist/core/agent-session-types.d.ts +5 -0
  152. package/dist/core/compaction/compaction.d.ts +6 -0
  153. package/dist/core/compaction/model-resolver.d.ts +1 -1
  154. package/dist/core/debug.code.js +3 -0
  155. package/dist/core/debug.code.js.map +1 -0
  156. package/dist/core/debug.impl.js +35 -2
  157. package/dist/core/debug.js +11 -7
  158. package/dist/core/default-model-api-prewarm.d.ts +5 -0
  159. package/dist/core/export-html/card-projection.code.js +257 -0
  160. package/dist/core/export-html/card-projection.code.js.map +1 -0
  161. package/dist/core/export-html/card-projection.impl.js +34 -255
  162. package/dist/core/export-html/card-projection.impl.js.map +1 -1
  163. package/dist/core/export-html/card-projection.js +11 -7
  164. package/dist/core/export-html/index.code.js +655 -0
  165. package/dist/core/export-html/index.code.js.map +1 -0
  166. package/dist/core/export-html/index.impl.js +30 -604
  167. package/dist/core/export-html/index.impl.js.map +1 -1
  168. package/dist/core/export-html/index.js +11 -7
  169. package/dist/core/export-html/json-spans.code.js +3 -0
  170. package/dist/core/export-html/json-spans.code.js.map +1 -0
  171. package/dist/core/export-html/json-spans.impl.js +35 -2
  172. package/dist/core/export-html/json-spans.js +11 -7
  173. package/dist/core/export-html/oversized-render-inputs.code.js +125 -0
  174. package/dist/core/export-html/oversized-render-inputs.code.js.map +1 -0
  175. package/dist/core/export-html/oversized-render-inputs.impl.js +31 -120
  176. package/dist/core/export-html/oversized-render-inputs.impl.js.map +1 -1
  177. package/dist/core/export-html/oversized-render-inputs.js +11 -7
  178. package/dist/core/export-html/tool-renderer.code.js +350 -0
  179. package/dist/core/export-html/tool-renderer.code.js.map +1 -0
  180. package/dist/core/export-html/tool-renderer.impl.js +33 -347
  181. package/dist/core/export-html/tool-renderer.impl.js.map +1 -1
  182. package/dist/core/export-html/tool-renderer.js +11 -7
  183. package/dist/core/extensions/jiti-loader.code.js +3 -0
  184. package/dist/core/extensions/jiti-loader.code.js.map +1 -0
  185. package/dist/core/extensions/jiti-loader.impl.js +35 -2
  186. package/dist/core/extensions/jiti-loader.js +11 -7
  187. package/dist/core/extensions/jiti-static-loader.code.js +3 -0
  188. package/dist/core/extensions/jiti-static-loader.code.js.map +1 -0
  189. package/dist/core/extensions/jiti-static-loader.impl.js +35 -2
  190. package/dist/core/extensions/jiti-static-loader.js +11 -7
  191. package/dist/core/extensions/loader-host-modules.code.js +3 -0
  192. package/dist/core/extensions/loader-host-modules.code.js.map +1 -0
  193. package/dist/core/extensions/loader-host-modules.impl.js +35 -2
  194. package/dist/core/extensions/loader-host-modules.js +11 -7
  195. package/dist/core/extensions/loader-virtual-modules.d.ts +1 -6
  196. package/dist/core/extensions/loader-virtual-modules.js +1 -1
  197. package/dist/core/extensions/runner-context.js +3 -3
  198. package/dist/core/extensions/session-events.d.ts +4 -0
  199. package/dist/core/extensions/session-events.js.map +1 -1
  200. package/dist/core/intercom-broker-control-host.code.js +5 -0
  201. package/dist/core/intercom-broker-control-host.code.js.map +1 -0
  202. package/dist/core/intercom-broker-control-host.impl.js +35 -4
  203. package/dist/core/intercom-broker-control-host.js +11 -7
  204. package/dist/core/intercom-broker-control.code.js +63 -0
  205. package/dist/core/intercom-broker-control.code.js.map +1 -0
  206. package/dist/core/intercom-broker-control.d.ts +21 -0
  207. package/dist/core/intercom-broker-control.impl.js +35 -17
  208. package/dist/core/intercom-broker-control.impl.js.map +1 -1
  209. package/dist/core/intercom-broker-control.js +11 -7
  210. package/dist/core/package-manager-storage-adapters.code.js +3 -0
  211. package/dist/core/package-manager-storage-adapters.code.js.map +1 -0
  212. package/dist/core/package-manager-storage-adapters.impl.js +35 -2
  213. package/dist/core/package-manager-storage-adapters.js +11 -7
  214. package/dist/core/process-start-token.d.ts +8 -2
  215. package/dist/core/process-tree-containment.d.ts +27 -0
  216. package/dist/core/queued-message-delivery.d.ts +5 -2
  217. package/dist/core/resume/blueprint/process.d.ts +3 -1
  218. package/dist/core/sdk.code.js +9 -0
  219. package/dist/core/sdk.code.js.map +1 -0
  220. package/dist/core/sdk.impl.js +35 -8
  221. package/dist/core/sdk.js +11 -7
  222. package/dist/core/session-manager-core.d.ts +15 -5
  223. package/dist/core/session-manager-core.js +195 -38
  224. package/dist/core/session-manager-core.js.map +1 -1
  225. package/dist/core/session-manager-list.code.js +3 -0
  226. package/dist/core/session-manager-list.code.js.map +1 -0
  227. package/dist/core/session-manager-list.impl.js +35 -2
  228. package/dist/core/session-manager-list.js +11 -7
  229. package/dist/core/session-manager-types.d.ts +20 -0
  230. package/dist/core/session-manager.code.js +8 -0
  231. package/dist/core/session-manager.code.js.map +1 -0
  232. package/dist/core/session-manager.d.ts +1 -1
  233. package/dist/core/session-manager.impl.js +35 -7
  234. package/dist/core/session-manager.js +11 -7
  235. package/dist/core/session-storage.code.js +3 -0
  236. package/dist/core/session-storage.code.js.map +1 -0
  237. package/dist/core/session-storage.impl.js +35 -2
  238. package/dist/core/session-storage.js +11 -7
  239. package/dist/core/storage/file-identity.d.ts +3 -0
  240. package/dist/core/storage/file-identity.js +296 -86
  241. package/dist/core/storage/file-identity.js.map +1 -1
  242. package/dist/core/storage/index.d.ts +1 -1
  243. package/dist/core/storage/index.js +52 -7
  244. package/dist/core/storage/index.js.map +1 -1
  245. package/dist/core/storage/node-sqlite-thread.js +47 -2
  246. package/dist/core/storage/node-sqlite.js +49 -4
  247. package/dist/core/storage/node-sqlite.js.map +1 -1
  248. package/dist/core/storage/offline-snapshot-file.code.js +37 -0
  249. package/dist/core/storage/offline-snapshot-file.code.js.map +1 -0
  250. package/dist/core/storage/offline-snapshot-file.impl.js +33 -34
  251. package/dist/core/storage/offline-snapshot-file.impl.js.map +1 -1
  252. package/dist/core/storage/offline-snapshot-file.js +11 -7
  253. package/dist/core/storage/provider.js +52 -7
  254. package/dist/core/storage/selection.js +49 -4
  255. package/dist/core/storage/session/branch-fork-source.code.js +146 -0
  256. package/dist/core/storage/session/branch-fork-source.code.js.map +1 -0
  257. package/dist/core/storage/session/branch-fork-source.impl.js +32 -97
  258. package/dist/core/storage/session/branch-fork-source.impl.js.map +1 -1
  259. package/dist/core/storage/session/branch-fork-source.js +11 -7
  260. package/dist/core/storage/session/card-view.code.js +60 -0
  261. package/dist/core/storage/session/card-view.code.js.map +1 -0
  262. package/dist/core/storage/session/card-view.impl.js +34 -58
  263. package/dist/core/storage/session/card-view.impl.js.map +1 -1
  264. package/dist/core/storage/session/card-view.js +11 -7
  265. package/dist/core/storage/session/child-reader.code.js +139 -0
  266. package/dist/core/storage/session/child-reader.code.js.map +1 -0
  267. package/dist/core/storage/session/child-reader.d.ts +1 -0
  268. package/dist/core/storage/session/child-reader.impl.js +33 -91
  269. package/dist/core/storage/session/child-reader.impl.js.map +1 -1
  270. package/dist/core/storage/session/child-reader.js +11 -7
  271. package/dist/core/storage/session/chunked-resume-projection.code.js +3 -0
  272. package/dist/core/storage/session/chunked-resume-projection.code.js.map +1 -0
  273. package/dist/core/storage/session/chunked-resume-projection.impl.js +35 -2
  274. package/dist/core/storage/session/chunked-resume-projection.js +11 -7
  275. package/dist/core/storage/session/expanded-child-details.code.js +684 -0
  276. package/dist/core/storage/session/expanded-child-details.code.js.map +1 -0
  277. package/dist/core/storage/session/expanded-child-details.impl.js +31 -634
  278. package/dist/core/storage/session/expanded-child-details.impl.js.map +1 -1
  279. package/dist/core/storage/session/expanded-child-details.js +11 -7
  280. package/dist/core/storage/session/fork-row-bytes.code.js +3 -0
  281. package/dist/core/storage/session/fork-row-bytes.code.js.map +1 -0
  282. package/dist/core/storage/session/fork-row-bytes.impl.js +35 -2
  283. package/dist/core/storage/session/fork-row-bytes.js +11 -7
  284. package/dist/core/storage/session/fork-row-index.code.js +3 -0
  285. package/dist/core/storage/session/fork-row-index.code.js.map +1 -0
  286. package/dist/core/storage/session/fork-row-index.impl.js +35 -2
  287. package/dist/core/storage/session/fork-row-index.js +11 -7
  288. package/dist/core/storage/session/fork-staging.code.js +580 -0
  289. package/dist/core/storage/session/fork-staging.code.js.map +1 -0
  290. package/dist/core/storage/session/fork-staging.impl.js +30 -574
  291. package/dist/core/storage/session/fork-staging.impl.js.map +1 -1
  292. package/dist/core/storage/session/fork-staging.js +11 -7
  293. package/dist/core/storage/session/fork-window.code.js +522 -0
  294. package/dist/core/storage/session/fork-window.code.js.map +1 -0
  295. package/dist/core/storage/session/fork-window.impl.js +30 -471
  296. package/dist/core/storage/session/fork-window.impl.js.map +1 -1
  297. package/dist/core/storage/session/fork-window.js +11 -7
  298. package/dist/core/storage/session/history-pages.code.js +3 -0
  299. package/dist/core/storage/session/history-pages.code.js.map +1 -0
  300. package/dist/core/storage/session/history-pages.impl.js +35 -2
  301. package/dist/core/storage/session/history-pages.js +11 -7
  302. package/dist/core/storage/session/jsonl-entry-projection.code.js +3 -0
  303. package/dist/core/storage/session/jsonl-entry-projection.code.js.map +1 -0
  304. package/dist/core/storage/session/jsonl-entry-projection.impl.js +35 -2
  305. package/dist/core/storage/session/jsonl-entry-projection.js +11 -7
  306. package/dist/core/storage/session/jsonl-session-store.code.js +3 -0
  307. package/dist/core/storage/session/jsonl-session-store.code.js.map +1 -0
  308. package/dist/core/storage/session/jsonl-session-store.impl.js +35 -2
  309. package/dist/core/storage/session/jsonl-session-store.js +11 -7
  310. package/dist/core/storage/session/memory-session-store.code.js +3 -0
  311. package/dist/core/storage/session/memory-session-store.code.js.map +1 -0
  312. package/dist/core/storage/session/memory-session-store.impl.js +35 -2
  313. package/dist/core/storage/session/memory-session-store.js +11 -7
  314. package/dist/core/storage/session/pinned-branch-resume.code.js +117 -0
  315. package/dist/core/storage/session/pinned-branch-resume.code.js.map +1 -0
  316. package/dist/core/storage/session/pinned-branch-resume.impl.js +33 -69
  317. package/dist/core/storage/session/pinned-branch-resume.impl.js.map +1 -1
  318. package/dist/core/storage/session/pinned-branch-resume.js +11 -7
  319. package/dist/core/storage/session/released-history-files.code.js +465 -0
  320. package/dist/core/storage/session/released-history-files.code.js.map +1 -0
  321. package/dist/core/storage/session/released-history-files.impl.js +32 -461
  322. package/dist/core/storage/session/released-history-files.impl.js.map +1 -1
  323. package/dist/core/storage/session/released-history-files.js +11 -7
  324. package/dist/core/storage/session/resident-fork-rows.code.js +57 -0
  325. package/dist/core/storage/session/resident-fork-rows.code.js.map +1 -0
  326. package/dist/core/storage/session/resident-fork-rows.impl.js +32 -53
  327. package/dist/core/storage/session/resident-fork-rows.impl.js.map +1 -1
  328. package/dist/core/storage/session/resident-fork-rows.js +11 -7
  329. package/dist/core/storage/session/session-resume.code.js +3 -0
  330. package/dist/core/storage/session/session-resume.code.js.map +1 -0
  331. package/dist/core/storage/session/session-resume.impl.js +35 -2
  332. package/dist/core/storage/session/session-resume.js +11 -7
  333. package/dist/core/storage/session/snapshot-cut.code.js +3 -0
  334. package/dist/core/storage/session/snapshot-cut.code.js.map +1 -0
  335. package/dist/core/storage/session/snapshot-cut.impl.js +35 -2
  336. package/dist/core/storage/session/snapshot-cut.js +11 -7
  337. package/dist/core/storage/session/snapshot-history.code.js +107 -0
  338. package/dist/core/storage/session/snapshot-history.code.js.map +1 -0
  339. package/dist/core/storage/session/snapshot-history.impl.js +34 -60
  340. package/dist/core/storage/session/snapshot-history.impl.js.map +1 -1
  341. package/dist/core/storage/session/snapshot-history.js +11 -7
  342. package/dist/core/storage/session/sql-session-store.code.js +3 -0
  343. package/dist/core/storage/session/sql-session-store.code.js.map +1 -0
  344. package/dist/core/storage/session/sql-session-store.impl.js +35 -2
  345. package/dist/core/storage/session/sql-session-store.js +11 -7
  346. package/dist/core/storage/session/tree-outline.code.js +3 -0
  347. package/dist/core/storage/session/tree-outline.code.js.map +1 -0
  348. package/dist/core/storage/session/tree-outline.impl.js +35 -2
  349. package/dist/core/storage/session/tree-outline.js +11 -7
  350. package/dist/core/storage/session/tree-presentation.code.js +342 -0
  351. package/dist/core/storage/session/tree-presentation.code.js.map +1 -0
  352. package/dist/core/storage/session/tree-presentation.impl.js +31 -337
  353. package/dist/core/storage/session/tree-presentation.impl.js.map +1 -1
  354. package/dist/core/storage/session/tree-presentation.js +11 -7
  355. package/dist/core/storage/session/types.d.ts +26 -0
  356. package/dist/core/storage/storage-status.code.js +3 -0
  357. package/dist/core/storage/storage-status.code.js.map +1 -0
  358. package/dist/core/storage/storage-status.impl.js +35 -2
  359. package/dist/core/storage/storage-status.js +11 -7
  360. package/dist/core/storage/team.code.js +3 -0
  361. package/dist/core/storage/team.code.js.map +1 -0
  362. package/dist/core/storage/team.impl.js +35 -2
  363. package/dist/core/storage/team.js +11 -7
  364. package/dist/core/structured-output/index.code.js +3 -0
  365. package/dist/core/structured-output/index.code.js.map +1 -0
  366. package/dist/core/structured-output/index.impl.js +35 -2
  367. package/dist/core/structured-output/index.js +11 -7
  368. package/dist/core/tasks/command-output.d.ts +4 -1
  369. package/dist/core/tasks/supervisor.d.ts +2 -0
  370. package/dist/core/tasks/task-completion-entry.code.js +254 -0
  371. package/dist/core/tasks/task-completion-entry.code.js.map +1 -0
  372. package/dist/core/tasks/task-completion-entry.impl.js +33 -251
  373. package/dist/core/tasks/task-completion-entry.impl.js.map +1 -1
  374. package/dist/core/tasks/task-completion-entry.js +11 -7
  375. package/dist/core/tasks/task-file-history.code.js +424 -0
  376. package/dist/core/tasks/task-file-history.code.js.map +1 -0
  377. package/dist/core/tasks/task-file-history.impl.js +32 -375
  378. package/dist/core/tasks/task-file-history.impl.js.map +1 -1
  379. package/dist/core/tasks/task-file-history.js +11 -7
  380. package/dist/core/tasks/{task-reference-archive.impl.js → task-reference-archive.code.js} +51 -6
  381. package/dist/core/tasks/{task-reference-archive.impl.js.map → task-reference-archive.code.js.map} +1 -1
  382. package/dist/core/tasks/task-reference-archive.js +11 -7
  383. package/dist/core/tasks/{task-reference-identity.impl.js → task-reference-identity.code.js} +1 -1
  384. package/dist/core/tasks/{task-reference-identity.impl.js.map → task-reference-identity.code.js.map} +1 -1
  385. package/dist/core/tasks/task-reference-identity.js +11 -7
  386. package/dist/core/tasks/task-reference-stream.code.js +3 -0
  387. package/dist/core/tasks/task-reference-stream.code.js.map +1 -0
  388. package/dist/core/tasks/task-reference-stream.impl.js +35 -2
  389. package/dist/core/tasks/task-reference-stream.js +11 -7
  390. package/dist/core/tasks/task-unsaved-answer.code.js +3 -0
  391. package/dist/core/tasks/task-unsaved-answer.code.js.map +1 -0
  392. package/dist/core/tasks/task-unsaved-answer.impl.js +35 -2
  393. package/dist/core/tasks/task-unsaved-answer.js +11 -7
  394. package/dist/core/tasks/task-view-source.code.js +3 -0
  395. package/dist/core/tasks/task-view-source.code.js.map +1 -0
  396. package/dist/core/tasks/task-view-source.d.ts +9 -0
  397. package/dist/core/tasks/task-view-source.impl.js +35 -2
  398. package/dist/core/tasks/task-view-source.js +12 -8
  399. package/dist/core/tools/read-url.code.js +1530 -0
  400. package/dist/core/tools/read-url.code.js.map +1 -0
  401. package/dist/core/tools/read-url.impl.js +30 -1524
  402. package/dist/core/tools/read-url.impl.js.map +1 -1
  403. package/dist/core/tools/read-url.js +11 -7
  404. package/dist/core/worktree-snapshot/blob-store.js +50 -5
  405. package/dist/core/worktree-snapshot/errors.code.js +6 -0
  406. package/dist/core/worktree-snapshot/errors.code.js.map +1 -0
  407. package/dist/core/worktree-snapshot/errors.impl.js +35 -5
  408. package/dist/core/worktree-snapshot/errors.js +11 -7
  409. package/dist/core/worktree-snapshot/session-index-reset.code.js +136 -0
  410. package/dist/core/worktree-snapshot/session-index-reset.code.js.map +1 -0
  411. package/dist/core/worktree-snapshot/session-index-reset.impl.js +34 -134
  412. package/dist/core/worktree-snapshot/session-index-reset.impl.js.map +1 -1
  413. package/dist/core/worktree-snapshot/session-index-reset.js +11 -7
  414. package/dist/extensions/codemode/execute.code.js +618 -0
  415. package/dist/extensions/codemode/execute.code.js.map +1 -0
  416. package/dist/extensions/codemode/execute.impl.js +30 -612
  417. package/dist/extensions/codemode/execute.impl.js.map +1 -1
  418. package/dist/extensions/codemode/execute.js +11 -7
  419. package/dist/extensions/codemode/renderer.code.js +110 -0
  420. package/dist/extensions/codemode/renderer.code.js.map +1 -0
  421. package/dist/extensions/codemode/renderer.impl.js +33 -107
  422. package/dist/extensions/codemode/renderer.impl.js.map +1 -1
  423. package/dist/extensions/codemode/renderer.js +11 -7
  424. package/dist/extensions/mcp/cli.code.js +565 -0
  425. package/dist/extensions/mcp/cli.code.js.map +1 -0
  426. package/dist/extensions/mcp/cli.impl.js +32 -561
  427. package/dist/extensions/mcp/cli.impl.js.map +1 -1
  428. package/dist/extensions/mcp/cli.js +11 -7
  429. package/dist/extensions/mcp/cli.lazy.code.js +52 -0
  430. package/dist/extensions/mcp/cli.lazy.code.js.map +1 -0
  431. package/dist/extensions/mcp/cli.lazy.impl.js +36 -7
  432. package/dist/extensions/mcp/cli.lazy.impl.js.map +1 -1
  433. package/dist/extensions/mcp/cli.lazy.js +11 -7
  434. package/dist/extensions/mcp/client/transports/stdio.d.ts +2 -0
  435. package/dist/extensions/mcp/runtime.code.js +5 -0
  436. package/dist/extensions/mcp/runtime.code.js.map +1 -0
  437. package/dist/extensions/mcp/runtime.impl.js +35 -4
  438. package/dist/extensions/mcp/runtime.js +11 -7
  439. package/dist/index.d.ts +1 -1
  440. package/dist/index.js +8 -8
  441. package/dist/main-first-time-setup.code.js +12 -0
  442. package/dist/main-first-time-setup.code.js.map +1 -0
  443. package/dist/main-first-time-setup.impl.js +35 -11
  444. package/dist/main-first-time-setup.impl.js.map +1 -1
  445. package/dist/main-first-time-setup.js +11 -7
  446. package/dist/main.d.ts +1 -1
  447. package/dist/main.js +2 -2
  448. package/dist/modes/interactive/agent-view/agent-view-switcher.d.ts +6 -1
  449. package/dist/modes/interactive/agent-view/contracts.d.ts +4 -0
  450. package/dist/modes/interactive/chat-reader-records.d.ts +1 -1
  451. package/dist/modes/interactive/components/stored-tree-view.code.js +338 -0
  452. package/dist/modes/interactive/components/stored-tree-view.code.js.map +1 -0
  453. package/dist/modes/interactive/components/stored-tree-view.impl.js +33 -290
  454. package/dist/modes/interactive/components/stored-tree-view.impl.js.map +1 -1
  455. package/dist/modes/interactive/components/stored-tree-view.js +11 -7
  456. package/dist/modes/interactive/components/task-selection-state.d.ts +8 -3
  457. package/dist/modes/interactive/components/task-transcript-page.d.ts +1 -0
  458. package/dist/modes/interactive/components/user-message-selector-archive.code.js +191 -0
  459. package/dist/modes/interactive/components/user-message-selector-archive.code.js.map +1 -0
  460. package/dist/modes/interactive/components/user-message-selector-archive.impl.js +34 -189
  461. package/dist/modes/interactive/components/user-message-selector-archive.impl.js.map +1 -1
  462. package/dist/modes/interactive/components/user-message-selector-archive.js +11 -7
  463. package/dist/modes/interactive/interactive-mode-base.d.ts +6 -0
  464. package/dist/modes/interactive/interactive-mode.js +1 -1
  465. package/dist/modes/interactive/interactive-queueing.d.ts +4 -0
  466. package/dist/modes/interactive/interactive-render-chat.d.ts +22 -0
  467. package/dist/modes/interactive/interactive-startup.d.ts +2 -0
  468. package/dist/modes/interactive/program-status-reporter.d.ts +2 -1
  469. package/dist/modes/interactive/startup-shell-eligibility.js +1 -1
  470. package/dist/modes/interactive/steering-queue-controller.d.ts +4 -0
  471. package/dist/modes/interactive/theme/theme-schema-factory.d.ts +26 -0
  472. package/dist/modes/interactive/theme/theme-schema.d.ts +4 -5
  473. package/dist/modes/interactive-engine/engine-prewarm.d.ts +30 -5
  474. package/dist/modes/interactive-engine/engine-prewarm.js +1 -1
  475. package/dist/modes/interactive-engine/isolated-runtime.d.ts +7 -0
  476. package/dist/modes/interactive-engine/protocol.d.ts +32 -1
  477. package/dist/modes/rpc/agent-view-rpc-types.d.ts +12 -1
  478. package/dist/modes/rpc/agent-view-rpc-types.js.map +1 -1
  479. package/dist/modes/rpc/rpc-client-api.d.ts +3 -1
  480. package/dist/modes/rpc/rpc-types.d.ts +12 -0
  481. package/dist/package-manager-cli.code.js +1140 -0
  482. package/dist/package-manager-cli.code.js.map +1 -0
  483. package/dist/package-manager-cli.impl.js +36 -1067
  484. package/dist/package-manager-cli.impl.js.map +1 -1
  485. package/dist/package-manager-cli.js +11 -7
  486. package/dist/rpc-entry.js +2 -2
  487. package/dist/startup-files.json +1 -1
  488. package/dist/startup-stages/10.js +1 -1
  489. package/dist/startup-stages/11.js +1 -1
  490. package/dist/startup-stages/12.js +1 -1
  491. package/dist/startup-stages/13.js +1 -0
  492. package/dist/startup-stages/2.js +1 -7
  493. package/dist/startup-stages/3.js +6 -2
  494. package/dist/startup-stages/4.js +2 -1
  495. package/dist/startup-stages/5.js +1 -7
  496. package/dist/startup-stages/6.js +7 -10
  497. package/dist/startup-stages/7.js +10 -3
  498. package/dist/startup-stages/8.js +3 -6
  499. package/dist/startup-stages/9.js +6 -1
  500. package/dist/startup-stages/stages.json +1 -1
  501. package/dist/utils/canonical-path.js +2 -0
  502. package/dist/utils/canonical-path.js.map +1 -1
  503. package/dist/utils/child-process.d.ts +41 -1
  504. package/dist/utils/compile-cache-warmup-host.js +63 -18
  505. package/dist/utils/compile-cache-warmup-host.js.map +1 -1
  506. package/dist/utils/credential-redaction.d.ts +50 -1
  507. package/dist/utils/interactive-engine-bootstrap.d.ts +2 -0
  508. package/dist/utils/interactive-engine-env.d.ts +2 -0
  509. package/dist/utils/memoize-async.d.ts +32 -0
  510. package/dist/utils/memoize-async.js +91 -0
  511. package/dist/utils/memoize-async.js.map +1 -0
  512. package/dist/utils/photon.js +19 -29
  513. package/dist/utils/photon.js.map +1 -1
  514. package/dist/utils/shell.d.ts +7 -4
  515. package/dist/utils/startup-database-spare.code.js +108 -0
  516. package/dist/utils/startup-database-spare.code.js.map +1 -0
  517. package/dist/utils/startup-database-spare.impl.js +33 -105
  518. package/dist/utils/startup-database-spare.impl.js.map +1 -1
  519. package/dist/utils/startup-database-spare.js +11 -7
  520. package/dist/utils/tools-manager.code.js +3 -0
  521. package/dist/utils/tools-manager.code.js.map +1 -0
  522. package/dist/utils/tools-manager.impl.js +35 -2
  523. package/dist/utils/tools-manager.js +11 -7
  524. package/dist/utils/windows-cwd.js +585 -0
  525. package/dist/utils/windows-cwd.js.map +1 -0
  526. package/docs/extensions.md +1 -1
  527. package/docs/getting-started/installation.md +2 -0
  528. package/docs/intercom/operations.md +1 -0
  529. package/docs/reference/cli.md +1 -1
  530. package/package.json +24 -24
  531. package/dist/_shared/mode-shared-HP7GUA7J.js.map +0 -1
  532. package/dist/_shared/p1a-prewarm-YK3KDTLN.js.map +0 -1
  533. package/dist/_shared/p1b-elig-PXQA2FYP.js.map +0 -1
  534. package/dist/_shared/startup-0-0-X4NF3GKM.js.map +0 -1
  535. package/dist/_shared/startup-0-1-7QTG6VJZ.js.map +0 -1
  536. package/dist/_shared/startup-0-2-KFDYPDJK.js.map +0 -1
  537. package/dist/_shared/startup-8-1-KQJBDKRU.js.map +0 -1
@@ -0,0 +1,3482 @@
1
+ import { __commonJSMin, __exportAll, __require, __toESM } from "./rolldown-runtime-BGM3D5V3.js";
2
+ import nodeModule, { createRequire } from "node:module";
3
+ import { lstat, mkdtemp, readFile, realpath, rename, rm, stat, writeFile } from "node:fs/promises";
4
+ import { accessSync, constants, existsSync, readFileSync, realpathSync } from "fs";
5
+ import { basename, dirname, join, resolve, sep, win32 } from "path";
6
+ import { availableParallelism, constants as constants$1, homedir, setPriority, tmpdir, totalmem, uptime } from "node:os";
7
+ import { basename as basename$1, dirname as dirname$1, isAbsolute as isAbsolute$1, join as join$1, posix, relative as relative$1, resolve as resolve$1, sep as sep$1, win32 as win32$1 } from "node:path";
8
+ import { fileURLToPath, pathToFileURL } from "node:url";
9
+ import { spawn, spawnSync } from "node:child_process";
10
+ import { findHelperExecutable, findHelperExecutableAsync, helperLaunch, helperLaunchAsync, missingHelperOptions } from "@bastani/atomic-tui/dist/helper-programs/index.js";
11
+ import { canonicalizePath as canonicalizePath$1, canonicalizePathAsync as canonicalizePathAsync$1, createSessionCwdMatcher, createSessionCwdMatcherAsync as createSessionCwdMatcherAsync$1 } from "../utils/canonical-path.js";
12
+ import { homedir as homedir$1 } from "os";
13
+ import { pathExists } from "../utils/path-exists.js";
14
+ import { appendFileSync, existsSync as existsSync$1, mkdirSync as mkdirSync$1, readFileSync as readFileSync$1, rmSync as rmSync$1 } from "node:fs";
15
+ import { Worker } from "node:worker_threads";
16
+ import { EVAL_WORKER_BUILTIN, evalWorkerExecArgv } from "../utils/worker-threads.js";
17
+ import { cachedDataVersionTag, getHeapStatistics, setFlagsFromString } from "node:v8";
18
+ import { nodeOptionsFromEnvironment, splitNodeOptions, startupNodeOptions } from "@bastani/atomic-codemode/node-options";
19
+ // dist/core/builtin-install-layout.js
20
+ const BUILTIN_PACKAGE_DIR_NAMES = [
21
+ "subagents",
22
+ "mcp",
23
+ "web-access",
24
+ "intercom"
25
+ ];
26
+ /** Source-checkout extension entries. Discovery still loads these in a git tree. */
27
+ const SOURCE_EXTENSION_ENTRIES = {
28
+ subagents: "src/extension/index.ts",
29
+ mcp: "index.ts",
30
+ "web-access": "index.ts",
31
+ intercom: "index.ts"
32
+ };
33
+ /** Installed/npm extension entries after copy-builtin-packages prebundles them. */
34
+ const INSTALLED_EXTENSION_ENTRIES = {
35
+ subagents: "src/extension/index.bundle.mjs",
36
+ mcp: "index.bundle.mjs",
37
+ "web-access": "index.bundle.mjs",
38
+ intercom: "index.bundle.mjs"
39
+ };
40
+ function requiredEntriesForBuiltin(dirName) {
41
+ return [INSTALLED_EXTENSION_ENTRIES[dirName], SOURCE_EXTENSION_ENTRIES[dirName]];
42
+ }
43
+ // dist/utils/text.js
44
+ /** Split a leading UTF-8 byte order mark from decoded text. */
45
+ function splitBom(content) {
46
+ return content.startsWith("") ? {
47
+ bom: "",
48
+ text: content.slice(1)
49
+ } : {
50
+ bom: "",
51
+ text: content
52
+ };
53
+ }
54
+ /** Remove a leading UTF-8 byte order mark from decoded text. */
55
+ function stripBom(content) {
56
+ return splitBom(content).text;
57
+ }
58
+ // dist/config-package-identity.js
59
+ const COMPANION_BUILTIN_PACKAGE_NAMES = BUILTIN_PACKAGE_DIR_NAMES.map((dirName) => `@bastani/${dirName}`);
60
+ function isCompanionBuiltinPackageName(name) {
61
+ return name !== void 0 && COMPANION_BUILTIN_PACKAGE_NAMES.includes(name);
62
+ }
63
+ function packageJsonDefinesAppIdentity(pkg) {
64
+ if (pkg.name === "@bastani/atomic" || pkg.name === "@mariozechner/pi") return true;
65
+ return pkg.atomicConfig !== void 0 || pkg.piConfig !== void 0;
66
+ }
67
+ /**
68
+ * Walk from a bundled or compiled module directory to the Atomic app package.
69
+ *
70
+ * Prebundled companion extensions live under `dist/builtin/<name>/` with their
71
+ * own `package.json`. The first package.json from those bundles is
72
+ * a companion such as `@bastani/subagents`, which must not become APP_NAME.
73
+ */
74
+ function resolvePackageDirFrom(startDir) {
75
+ let dir = startDir;
76
+ let firstPackageDir;
77
+ while (dir !== dirname(dir)) {
78
+ const packageJsonPath = join(dir, "package.json");
79
+ if (existsSync(packageJsonPath)) {
80
+ firstPackageDir ??= dir;
81
+ if (shouldUsePackageDir(readPackageIdentity(packageJsonPath))) return dir;
82
+ }
83
+ dir = dirname(dir);
84
+ }
85
+ return firstPackageDir ?? startDir;
86
+ }
87
+ function shouldUsePackageDir(pkg) {
88
+ if (packageJsonDefinesAppIdentity(pkg)) return true;
89
+ return !isCompanionBuiltinPackageName(pkg.name);
90
+ }
91
+ function isJsonValue(value) {
92
+ if (value === null || typeof value === "boolean" || typeof value === "string") return true;
93
+ if (typeof value === "number") return Number.isFinite(value);
94
+ if (Array.isArray(value)) return value.every(isJsonValue);
95
+ if (typeof value !== "object" || Object.getPrototypeOf(value) !== Object.prototype) return false;
96
+ return Object.values(value).every(isJsonValue);
97
+ }
98
+ function isJsonObject(value) {
99
+ return value !== null && typeof value === "object" && !Array.isArray(value);
100
+ }
101
+ function readPackageIdentity(packageJsonPath) {
102
+ try {
103
+ const parsed = JSON.parse(stripBom(readFileSync(packageJsonPath, "utf-8")));
104
+ if (!isJsonValue(parsed) || !isJsonObject(parsed)) return {};
105
+ const name = parsed.name;
106
+ const atomicConfig = parsed.atomicConfig;
107
+ const piConfig = parsed.piConfig;
108
+ return {
109
+ ...typeof name === "string" ? { name } : {},
110
+ ...atomicConfig !== void 0 && isJsonObject(atomicConfig) ? { atomicConfig } : {},
111
+ ...piConfig !== void 0 && isJsonObject(piConfig) ? { piConfig } : {}
112
+ };
113
+ } catch {}
114
+ return {};
115
+ }
116
+ // ../../node_modules/isexe/windows.js
117
+ var require_windows = /* @__PURE__ */ __commonJSMin(((exports, module) => {
118
+ module.exports = isexe;
119
+ isexe.sync = sync;
120
+ var fs = __require("fs");
121
+ function checkPathExt(path, options) {
122
+ var pathext = options.pathExt !== void 0 ? options.pathExt : process.env.PATHEXT;
123
+ if (!pathext) return true;
124
+ pathext = pathext.split(";");
125
+ if (pathext.indexOf("") !== -1) return true;
126
+ for (var i = 0; i < pathext.length; i++) {
127
+ var p = pathext[i].toLowerCase();
128
+ if (p && path.substr(-p.length).toLowerCase() === p) return true;
129
+ }
130
+ return false;
131
+ }
132
+ function checkStat(stat, path, options) {
133
+ if (!stat.isSymbolicLink() && !stat.isFile()) return false;
134
+ return checkPathExt(path, options);
135
+ }
136
+ function isexe(path, options, cb) {
137
+ fs.stat(path, function(er, stat) {
138
+ cb(er, er ? false : checkStat(stat, path, options));
139
+ });
140
+ }
141
+ function sync(path, options) {
142
+ return checkStat(fs.statSync(path), path, options);
143
+ }
144
+ }));
145
+ // ../../node_modules/isexe/mode.js
146
+ var require_mode = /* @__PURE__ */ __commonJSMin(((exports, module) => {
147
+ module.exports = isexe;
148
+ isexe.sync = sync;
149
+ var fs = __require("fs");
150
+ function isexe(path, options, cb) {
151
+ fs.stat(path, function(er, stat) {
152
+ cb(er, er ? false : checkStat(stat, options));
153
+ });
154
+ }
155
+ function sync(path, options) {
156
+ return checkStat(fs.statSync(path), options);
157
+ }
158
+ function checkStat(stat, options) {
159
+ return stat.isFile() && checkMode(stat, options);
160
+ }
161
+ function checkMode(stat, options) {
162
+ var mod = stat.mode;
163
+ var uid = stat.uid;
164
+ var gid = stat.gid;
165
+ var myUid = options.uid !== void 0 ? options.uid : process.getuid && process.getuid();
166
+ var myGid = options.gid !== void 0 ? options.gid : process.getgid && process.getgid();
167
+ var u = parseInt("100", 8);
168
+ var g = parseInt("010", 8);
169
+ var o = parseInt("001", 8);
170
+ var ug = u | g;
171
+ return mod & o || mod & g && gid === myGid || mod & u && uid === myUid || mod & ug && myUid === 0;
172
+ }
173
+ }));
174
+ // ../../node_modules/isexe/index.js
175
+ var require_isexe = /* @__PURE__ */ __commonJSMin(((exports, module) => {
176
+ __require("fs");
177
+ var core;
178
+ if (process.platform === "win32" || global.TESTING_WINDOWS) core = require_windows();
179
+ else core = require_mode();
180
+ module.exports = isexe;
181
+ isexe.sync = sync;
182
+ function isexe(path, options, cb) {
183
+ if (typeof options === "function") {
184
+ cb = options;
185
+ options = {};
186
+ }
187
+ if (!cb) {
188
+ if (typeof Promise !== "function") throw new TypeError("callback not provided");
189
+ return new Promise(function(resolve, reject) {
190
+ isexe(path, options || {}, function(er, is) {
191
+ if (er) reject(er);
192
+ else resolve(is);
193
+ });
194
+ });
195
+ }
196
+ core(path, options || {}, function(er, is) {
197
+ if (er) {
198
+ if (er.code === "EACCES" || options && options.ignoreErrors) {
199
+ er = null;
200
+ is = false;
201
+ }
202
+ }
203
+ cb(er, is);
204
+ });
205
+ }
206
+ function sync(path, options) {
207
+ try {
208
+ return core.sync(path, options || {});
209
+ } catch (er) {
210
+ if (options && options.ignoreErrors || er.code === "EACCES") return false;
211
+ else throw er;
212
+ }
213
+ }
214
+ }));
215
+ // ../../node_modules/which/which.js
216
+ var require_which = /* @__PURE__ */ __commonJSMin(((exports, module) => {
217
+ const isWindows = process.platform === "win32" || process.env.OSTYPE === "cygwin" || process.env.OSTYPE === "msys";
218
+ const path = __require("path");
219
+ const COLON = isWindows ? ";" : ":";
220
+ const isexe = require_isexe();
221
+ const getNotFoundError = (cmd) => Object.assign(/* @__PURE__ */ new Error(`not found: ${cmd}`), { code: "ENOENT" });
222
+ const getPathInfo = (cmd, opt) => {
223
+ const colon = opt.colon || COLON;
224
+ const pathEnv = cmd.match(/\//) || isWindows && cmd.match(/\\/) ? [""] : [...isWindows ? [process.cwd()] : [], ...(opt.path || process.env.PATH ||
225
+ /* istanbul ignore next: very unusual */ "").split(colon)];
226
+ const pathExtExe = isWindows ? opt.pathExt || process.env.PATHEXT || ".EXE;.CMD;.BAT;.COM" : "";
227
+ const pathExt = isWindows ? pathExtExe.split(colon) : [""];
228
+ if (isWindows) {
229
+ if (cmd.indexOf(".") !== -1 && pathExt[0] !== "") pathExt.unshift("");
230
+ }
231
+ return {
232
+ pathEnv,
233
+ pathExt,
234
+ pathExtExe
235
+ };
236
+ };
237
+ const which = (cmd, opt, cb) => {
238
+ if (typeof opt === "function") {
239
+ cb = opt;
240
+ opt = {};
241
+ }
242
+ if (!opt) opt = {};
243
+ const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt);
244
+ const found = [];
245
+ const step = (i) => new Promise((resolve, reject) => {
246
+ if (i === pathEnv.length) return opt.all && found.length ? resolve(found) : reject(getNotFoundError(cmd));
247
+ const ppRaw = pathEnv[i];
248
+ const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw;
249
+ const pCmd = path.join(pathPart, cmd);
250
+ const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd : pCmd;
251
+ resolve(subStep(p, i, 0));
252
+ });
253
+ const subStep = (p, i, ii) => new Promise((resolve, reject) => {
254
+ if (ii === pathExt.length) return resolve(step(i + 1));
255
+ const ext = pathExt[ii];
256
+ isexe(p + ext, { pathExt: pathExtExe }, (er, is) => {
257
+ if (!er && is) {
258
+ if (opt.all) found.push(p + ext);
259
+ else return resolve(p + ext);
260
+ }
261
+ return resolve(subStep(p, i, ii + 1));
262
+ });
263
+ });
264
+ return cb ? step(0).then((res) => cb(null, res), cb) : step(0);
265
+ };
266
+ const whichSync = (cmd, opt) => {
267
+ opt = opt || {};
268
+ const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt);
269
+ const found = [];
270
+ for (let i = 0; i < pathEnv.length; i++) {
271
+ const ppRaw = pathEnv[i];
272
+ const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw;
273
+ const pCmd = path.join(pathPart, cmd);
274
+ const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd : pCmd;
275
+ for (let j = 0; j < pathExt.length; j++) {
276
+ const cur = p + pathExt[j];
277
+ try {
278
+ if (isexe.sync(cur, { pathExt: pathExtExe })) {
279
+ if (opt.all) found.push(cur);
280
+ else return cur;
281
+ }
282
+ } catch (ex) {}
283
+ }
284
+ }
285
+ if (opt.all && found.length) return found;
286
+ if (opt.nothrow) return null;
287
+ throw getNotFoundError(cmd);
288
+ };
289
+ module.exports = which;
290
+ which.sync = whichSync;
291
+ }));
292
+ // ../../node_modules/path-key/index.js
293
+ var require_path_key = /* @__PURE__ */ __commonJSMin(((exports, module) => {
294
+ const pathKey = (options = {}) => {
295
+ const environment = options.env || process.env;
296
+ if ((options.platform || process.platform) !== "win32") return "PATH";
297
+ return Object.keys(environment).reverse().find((key) => key.toUpperCase() === "PATH") || "Path";
298
+ };
299
+ module.exports = pathKey;
300
+ module.exports.default = pathKey;
301
+ }));
302
+ // ../../node_modules/cross-spawn/lib/util/resolveCommand.js
303
+ var require_resolveCommand = /* @__PURE__ */ __commonJSMin(((exports, module) => {
304
+ const path = __require("path");
305
+ const which = require_which();
306
+ const getPathKey = require_path_key();
307
+ function resolveCommandAttempt(parsed, withoutPathExt) {
308
+ const env = parsed.options.env || process.env;
309
+ const cwd = process.cwd();
310
+ const hasCustomCwd = parsed.options.cwd != null;
311
+ const shouldSwitchCwd = hasCustomCwd && process.chdir !== void 0 && !process.chdir.disabled;
312
+ if (shouldSwitchCwd) try {
313
+ process.chdir(parsed.options.cwd);
314
+ } catch (err) {}
315
+ let resolved;
316
+ try {
317
+ resolved = which.sync(parsed.command, {
318
+ path: env[getPathKey({ env })],
319
+ pathExt: withoutPathExt ? path.delimiter : void 0
320
+ });
321
+ } catch (e) {} finally {
322
+ if (shouldSwitchCwd) process.chdir(cwd);
323
+ }
324
+ if (resolved) resolved = path.resolve(hasCustomCwd ? parsed.options.cwd : "", resolved);
325
+ return resolved;
326
+ }
327
+ function resolveCommand(parsed) {
328
+ return resolveCommandAttempt(parsed) || resolveCommandAttempt(parsed, true);
329
+ }
330
+ module.exports = resolveCommand;
331
+ }));
332
+ // ../../node_modules/cross-spawn/lib/util/escape.js
333
+ var require_escape = /* @__PURE__ */ __commonJSMin(((exports, module) => {
334
+ const metaCharsRegExp = /([()\][%!^"`<>&|;, *?])/g;
335
+ function escapeCommand(arg) {
336
+ arg = arg.replace(metaCharsRegExp, "^$1");
337
+ return arg;
338
+ }
339
+ function escapeArgument(arg, doubleEscapeMetaChars) {
340
+ arg = `${arg}`;
341
+ arg = arg.replace(/(?=(\\+?)?)\1"/g, "$1$1\\\"");
342
+ arg = arg.replace(/(?=(\\+?)?)\1$/, "$1$1");
343
+ arg = `"${arg}"`;
344
+ arg = arg.replace(metaCharsRegExp, "^$1");
345
+ if (doubleEscapeMetaChars) arg = arg.replace(metaCharsRegExp, "^$1");
346
+ return arg;
347
+ }
348
+ module.exports.command = escapeCommand;
349
+ module.exports.argument = escapeArgument;
350
+ }));
351
+ // ../../node_modules/shebang-regex/index.js
352
+ var require_shebang_regex = /* @__PURE__ */ __commonJSMin(((exports, module) => {
353
+ module.exports = /^#!(.*)/;
354
+ }));
355
+ // ../../node_modules/shebang-command/index.js
356
+ var require_shebang_command = /* @__PURE__ */ __commonJSMin(((exports, module) => {
357
+ const shebangRegex = require_shebang_regex();
358
+ module.exports = (string = "") => {
359
+ const match = string.match(shebangRegex);
360
+ if (!match) return null;
361
+ const [path, argument] = match[0].replace(/#! ?/, "").split(" ");
362
+ const binary = path.split("/").pop();
363
+ if (binary === "env") return argument;
364
+ return argument ? `${binary} ${argument}` : binary;
365
+ };
366
+ }));
367
+ // ../../node_modules/cross-spawn/lib/util/readShebang.js
368
+ var require_readShebang = /* @__PURE__ */ __commonJSMin(((exports, module) => {
369
+ const fs = __require("fs");
370
+ const shebangCommand = require_shebang_command();
371
+ function readShebang(command) {
372
+ const size = 150;
373
+ const buffer = Buffer.alloc(size);
374
+ let fd;
375
+ try {
376
+ fd = fs.openSync(command, "r");
377
+ fs.readSync(fd, buffer, 0, size, 0);
378
+ fs.closeSync(fd);
379
+ } catch (e) {}
380
+ return shebangCommand(buffer.toString());
381
+ }
382
+ module.exports = readShebang;
383
+ }));
384
+ // ../../node_modules/cross-spawn/lib/parse.js
385
+ var require_parse = /* @__PURE__ */ __commonJSMin(((exports, module) => {
386
+ const path = __require("path");
387
+ const resolveCommand = require_resolveCommand();
388
+ const escape = require_escape();
389
+ const readShebang = require_readShebang();
390
+ const isWin = process.platform === "win32";
391
+ const isExecutableRegExp = /\.(?:com|exe)$/i;
392
+ const isCmdShimRegExp = /node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;
393
+ function detectShebang(parsed) {
394
+ parsed.file = resolveCommand(parsed);
395
+ const shebang = parsed.file && readShebang(parsed.file);
396
+ if (shebang) {
397
+ parsed.args.unshift(parsed.file);
398
+ parsed.command = shebang;
399
+ return resolveCommand(parsed);
400
+ }
401
+ return parsed.file;
402
+ }
403
+ function parseNonShell(parsed) {
404
+ if (!isWin) return parsed;
405
+ const commandFile = detectShebang(parsed);
406
+ const needsShell = !isExecutableRegExp.test(commandFile);
407
+ if (parsed.options.forceShell || needsShell) {
408
+ const needsDoubleEscapeMetaChars = isCmdShimRegExp.test(commandFile);
409
+ parsed.command = path.normalize(parsed.command);
410
+ parsed.command = escape.command(parsed.command);
411
+ parsed.args = parsed.args.map((arg) => escape.argument(arg, needsDoubleEscapeMetaChars));
412
+ parsed.args = [
413
+ "/d",
414
+ "/s",
415
+ "/c",
416
+ `"${[parsed.command].concat(parsed.args).join(" ")}"`
417
+ ];
418
+ parsed.command = process.env.comspec || "cmd.exe";
419
+ parsed.options.windowsVerbatimArguments = true;
420
+ }
421
+ return parsed;
422
+ }
423
+ function parse(command, args, options) {
424
+ if (args && !Array.isArray(args)) {
425
+ options = args;
426
+ args = null;
427
+ }
428
+ args = args ? args.slice(0) : [];
429
+ options = Object.assign({}, options);
430
+ const parsed = {
431
+ command,
432
+ args,
433
+ options,
434
+ file: void 0,
435
+ original: {
436
+ command,
437
+ args
438
+ }
439
+ };
440
+ return options.shell ? parsed : parseNonShell(parsed);
441
+ }
442
+ module.exports = parse;
443
+ }));
444
+ // ../../node_modules/cross-spawn/lib/enoent.js
445
+ var require_enoent = /* @__PURE__ */ __commonJSMin(((exports, module) => {
446
+ const isWin = process.platform === "win32";
447
+ function notFoundError(original, syscall) {
448
+ return Object.assign(/* @__PURE__ */ new Error(`${syscall} ${original.command} ENOENT`), {
449
+ code: "ENOENT",
450
+ errno: "ENOENT",
451
+ syscall: `${syscall} ${original.command}`,
452
+ path: original.command,
453
+ spawnargs: original.args
454
+ });
455
+ }
456
+ function hookChildProcess(cp, parsed) {
457
+ if (!isWin) return;
458
+ const originalEmit = cp.emit;
459
+ cp.emit = function(name, arg1) {
460
+ if (name === "exit") {
461
+ const err = verifyENOENT(arg1, parsed);
462
+ if (err) return originalEmit.call(cp, "error", err);
463
+ }
464
+ return originalEmit.apply(cp, arguments);
465
+ };
466
+ }
467
+ function verifyENOENT(status, parsed) {
468
+ if (isWin && status === 1 && !parsed.file) return notFoundError(parsed.original, "spawn");
469
+ return null;
470
+ }
471
+ function verifyENOENTSync(status, parsed) {
472
+ if (isWin && status === 1 && !parsed.file) return notFoundError(parsed.original, "spawnSync");
473
+ return null;
474
+ }
475
+ module.exports = {
476
+ hookChildProcess,
477
+ verifyENOENT,
478
+ verifyENOENTSync,
479
+ notFoundError
480
+ };
481
+ }));
482
+ // ../../node_modules/cross-spawn/index.js
483
+ var require_cross_spawn = /* @__PURE__ */ __commonJSMin(((exports, module) => {
484
+ const cp = __require("child_process");
485
+ const parse = require_parse();
486
+ const enoent = require_enoent();
487
+ function spawn(command, args, options) {
488
+ const parsed = parse(command, args, options);
489
+ const spawned = cp.spawn(parsed.command, parsed.args, parsed.options);
490
+ enoent.hookChildProcess(spawned, parsed);
491
+ return spawned;
492
+ }
493
+ function spawnSync(command, args, options) {
494
+ const parsed = parse(command, args, options);
495
+ const result = cp.spawnSync(parsed.command, parsed.args, parsed.options);
496
+ result.error = result.error || enoent.verifyENOENTSync(result.status, parsed);
497
+ return result;
498
+ }
499
+ module.exports = spawn;
500
+ module.exports.spawn = spawn;
501
+ module.exports.sync = spawnSync;
502
+ module.exports._parse = parse;
503
+ module.exports._enoent = enoent;
504
+ }));
505
+ // dist/core/debug-errors.js
506
+ var import_cross_spawn = /* @__PURE__ */ __toESM(require_cross_spawn(), 1);
507
+ /** The family of debug output errors. */
508
+ var DebugError = class extends Error {
509
+ name = "DebugError";
510
+ code;
511
+ /** What to do about it, without the rest of the message. */
512
+ hint;
513
+ retryable = false;
514
+ constructor(code, message, hint, options) {
515
+ super(message, options);
516
+ this.code = code;
517
+ this.hint = hint;
518
+ }
519
+ /** The facts this error carries, as JSON-safe text. */
520
+ fields() {
521
+ return {};
522
+ }
523
+ };
524
+ /** A debug log file could not be written. Atomic keeps running; that debug output is lost. */
525
+ var DebugLogUnwritableError = class extends DebugError {
526
+ name = "DebugLogUnwritableError";
527
+ retryable = false;
528
+ path;
529
+ constructor(path, options) {
530
+ const hint = `Make ${dirname$1(path)} writable, or turn debug mode off.`;
531
+ super("debug-log-unwritable", `Debug log is not writable: ${path} (debug-log-unwritable). ${hint}`, hint, options);
532
+ this.path = path;
533
+ }
534
+ fields() {
535
+ return { path: this.path };
536
+ }
537
+ };
538
+ /** The debug setting was given something other than `true` or `false`. Nothing changed. */
539
+ var DebugConfigError = class extends DebugError {
540
+ name = "DebugConfigError";
541
+ retryable = false;
542
+ source;
543
+ field = "enabled";
544
+ /** The type of the value received, never the value itself. */
545
+ received;
546
+ constructor({ source, received }) {
547
+ const hint = "Pass true or false.";
548
+ super("invalid-setting", `Invalid debug setting: enabled is ${received}, not a boolean (invalid-setting). ${hint}`, hint);
549
+ this.source = source;
550
+ this.received = received;
551
+ }
552
+ fields() {
553
+ return {
554
+ source: this.source,
555
+ field: this.field,
556
+ received: this.received
557
+ };
558
+ }
559
+ };
560
+ const MAX_CAUSE_DEPTH = 8;
561
+ /** `error` as JSON-safe data, its cause chain cut after eight errors. {@link rehydrateDebugError} reverses it. */
562
+ function serializeDebugError(error, depth = 0) {
563
+ const serialized = {
564
+ name: error.name,
565
+ code: error.code,
566
+ message: error.message,
567
+ hint: error.hint,
568
+ retryable: error.retryable,
569
+ fields: error.fields()
570
+ };
571
+ const { cause } = error;
572
+ if (cause === void 0 || depth + 1 >= MAX_CAUSE_DEPTH) return serialized;
573
+ if (cause instanceof DebugError) return {
574
+ ...serialized,
575
+ cause: serializeDebugError(cause, depth + 1)
576
+ };
577
+ const other = cause instanceof Error ? cause : new Error(String(cause));
578
+ return {
579
+ ...serialized,
580
+ cause: {
581
+ name: other.name,
582
+ message: other.message
583
+ }
584
+ };
585
+ }
586
+ /** A {@link DebugError} whose class this process does not know; it keeps the name, code and fields it arrived with. */
587
+ var ForeignDebugError = class extends DebugError {
588
+ name;
589
+ retryable;
590
+ carried;
591
+ constructor(serialized, options) {
592
+ super(serialized.code, serialized.message, serialized.hint, options);
593
+ this.name = serialized.name;
594
+ this.retryable = serialized.retryable;
595
+ this.carried = serialized.fields;
596
+ }
597
+ fields() {
598
+ return this.carried;
599
+ }
600
+ };
601
+ function rehydrateCause(cause) {
602
+ if ("code" in cause) return rehydrateDebugError(cause);
603
+ const error = new Error(cause.message);
604
+ error.name = cause.name;
605
+ return error;
606
+ }
607
+ /** The error {@link serializeDebugError} described, as the same class with the same fields. */
608
+ function rehydrateDebugError(serialized) {
609
+ const options = serialized.cause === void 0 ? void 0 : { cause: rehydrateCause(serialized.cause) };
610
+ const { path, source, received } = serialized.fields;
611
+ if (serialized.name === "DebugLogUnwritableError" && path !== void 0) return new DebugLogUnwritableError(path, options);
612
+ if (serialized.name === "DebugConfigError" && (source === "rpc" || source === "sdk") && received !== void 0) return new DebugConfigError({
613
+ source,
614
+ received
615
+ });
616
+ return new ForeignDebugError(serialized, options);
617
+ }
618
+ const DEBUG_ERROR_NAMES = /* @__PURE__ */ new Set([
619
+ "DebugError",
620
+ "DebugLogUnwritableError",
621
+ "DebugConfigError"
622
+ ]);
623
+ const DEBUG_LOG_UNWRITABLE_NAMES = /* @__PURE__ */ new Set(["DebugLogUnwritableError"]);
624
+ const DEBUG_CONFIG_NAMES = /* @__PURE__ */ new Set(["DebugConfigError"]);
625
+ function hasStructure(value, names, code) {
626
+ if (typeof value !== "object" || value === null) return false;
627
+ const fields = value;
628
+ return names.has(fields.name) && typeof fields.code === "string" && (code === void 0 || fields.code === code);
629
+ }
630
+ /** Whether `value` is a {@link DebugError}, also one that crossed a realm or process boundary. */
631
+ function isDebugError(value) {
632
+ return value instanceof DebugError || hasStructure(value, DEBUG_ERROR_NAMES);
633
+ }
634
+ /** Whether `value` is a {@link DebugLogUnwritableError}, also one that crossed a realm or process boundary. */
635
+ function isDebugLogUnwritableError(value) {
636
+ return value instanceof DebugLogUnwritableError || hasStructure(value, DEBUG_LOG_UNWRITABLE_NAMES, "debug-log-unwritable");
637
+ }
638
+ /** Whether `value` is a {@link DebugConfigError}, also one that crossed a realm or process boundary. */
639
+ function isDebugConfigError(value) {
640
+ return value instanceof DebugConfigError || hasStructure(value, DEBUG_CONFIG_NAMES, "invalid-setting");
641
+ }
642
+ // dist/core/debug-setting.js
643
+ /** Carries the `debug` setting into child processes. Atomic sets it; users set `ATOMIC_DEBUG`. */
644
+ const DEBUG_SETTING_ENV = "ATOMIC_DEBUG_SETTING";
645
+ let debugSetting = process.env[DEBUG_SETTING_ENV] === "1";
646
+ /** Whether a parent Atomic process passed its debug setting down; only a process without one uses its saved setting. */
647
+ function inheritsDebugSetting(env = process.env) {
648
+ return env[DEBUG_SETTING_ENV] !== void 0;
649
+ }
650
+ const settingListeners = /* @__PURE__ */ new Set();
651
+ /** This process's `debug` setting: its saved value, a toggle in `/settings`, or what its parent passed down. */
652
+ function isDebugSettingOn() {
653
+ return debugSetting;
654
+ }
655
+ /**
656
+ * Sets this process's `debug` setting. Child processes started afterwards inherit it. Throws {@link DebugConfigError},
657
+ * changing nothing, when `enabled` is not a boolean.
658
+ */
659
+ function setDebugSetting(enabled, source = "sdk") {
660
+ if (typeof enabled !== "boolean") throw new DebugConfigError({
661
+ source,
662
+ received: enabled === null ? "null" : typeof enabled
663
+ });
664
+ if (enabled === debugSetting) return;
665
+ debugSetting = enabled;
666
+ for (const listener of settingListeners) listener(enabled);
667
+ }
668
+ /** Calls `listener` whenever this process's `debug` setting changes; returns the unsubscribe function. */
669
+ function onDebugSettingChange(listener) {
670
+ settingListeners.add(listener);
671
+ return () => settingListeners.delete(listener);
672
+ }
673
+ /** Writes this process's `debug` setting into `env`, the environment of a child process about to start. */
674
+ function applyDebugSettingToChildEnvironment(env) {
675
+ env[DEBUG_SETTING_ENV] = debugSetting ? "1" : "0";
676
+ }
677
+ // dist/core/storage/host-adapters.js
678
+ /**
679
+ * The storage adapters of the packages an Atomic process's host loaded, as the processes it starts receive them: a JSON
680
+ * object from each adapter name, `<package>` or `<package>/<name>`, to the absolute adapter module it selects.
681
+ */
682
+ const HOST_STORAGE_ADAPTERS_ENV = "ATOMIC_HOST_STORAGE_ADAPTERS";
683
+ const HOST_ADAPTERS = Symbol.for("@bastani/atomic/storage/host-adapters");
684
+ const registry = globalThis;
685
+ /** The adapters this process inherited from the process that started it. */
686
+ function inheritedAdapters() {
687
+ const adapters = /* @__PURE__ */ new Map();
688
+ const text = process.env[HOST_STORAGE_ADAPTERS_ENV];
689
+ if (text === void 0 || text.length === 0) return adapters;
690
+ let value;
691
+ try {
692
+ value = JSON.parse(text);
693
+ } catch {
694
+ return adapters;
695
+ }
696
+ if (value === null || typeof value !== "object" || Array.isArray(value)) return adapters;
697
+ for (const [name, module] of Object.entries(value)) if (typeof module === "string" && isAbsolute$1(module)) adapters.set(name, module);
698
+ return adapters;
699
+ }
700
+ function hostAdapters() {
701
+ registry[HOST_ADAPTERS] ??= inheritedAdapters();
702
+ return registry[HOST_ADAPTERS];
703
+ }
704
+ /** Makes `name` select the absolute adapter `module` in this process and the processes it starts; a registered name keeps its module. */
705
+ function addHostStorageAdapter(name, module) {
706
+ const adapters = hostAdapters();
707
+ if (!adapters.has(name)) adapters.set(name, module);
708
+ }
709
+ /** The adapter module `name` selects from the packages this process's host loaded, or undefined. */
710
+ function hostStorageAdapter(name) {
711
+ return hostAdapters().get(name);
712
+ }
713
+ /** The environment that passes this process's host-loaded adapters to a process it starts; empty without any. */
714
+ function hostStorageAdaptersEnvironment() {
715
+ const adapters = hostAdapters();
716
+ return adapters.size === 0 ? {} : { [HOST_STORAGE_ADAPTERS_ENV]: JSON.stringify(Object.fromEntries(adapters)) };
717
+ }
718
+ // dist/utils/agent-attribution.js
719
+ const ATOMIC_AI_AGENT = "atomic";
720
+ // dist/utils/child-process.js
721
+ const __atomicDistModuleUrl$4 = new URL("../utils/child-process.js", import.meta.url).href;
722
+ const EXIT_STDIO_IDLE_GRACE_MS = 100;
723
+ const EXIT_STDIO_ACTIVE_DRAIN_HARD_CAP_MS = 5e3;
724
+ const WINDOWS_EXIT_POLL_INTERVAL_MS = 50;
725
+ const WINDOWS_EXIT_CODE_GRACE_MS = 1e3;
726
+ var ChildProcessExitStatusUnknownError = class extends Error {
727
+ name = "ChildProcessExitStatusUnknownError";
728
+ pid;
729
+ constructor(pid) {
730
+ super(pid === void 0 ? "Child process exit status unknown" : `Child process ${pid} exit status unknown`);
731
+ this.pid = pid;
732
+ }
733
+ };
734
+ function isChildProcessExitStatusUnknownError(value) {
735
+ return value instanceof ChildProcessExitStatusUnknownError || value instanceof Error && value.name === "ChildProcessExitStatusUnknownError";
736
+ }
737
+ const NATIVE_WINDOWS_HOST = process.platform === "win32";
738
+ let nativeHoldWindowsProcessExit;
739
+ function loadNativeHoldWindowsProcessExit() {
740
+ if (!NATIVE_WINDOWS_HOST) return null;
741
+ if (nativeHoldWindowsProcessExit === void 0) try {
742
+ let binding;
743
+ try {
744
+ binding = createRequire(__atomicDistModuleUrl$4)("@bastani/atomic-natives");
745
+ } catch {
746
+ binding = createRequire(pathToFileURL(process.execPath).href)("@bastani/atomic-natives");
747
+ }
748
+ nativeHoldWindowsProcessExit = binding.holdWindowsProcessExit ?? null;
749
+ } catch {
750
+ nativeHoldWindowsProcessExit = null;
751
+ }
752
+ return nativeHoldWindowsProcessExit;
753
+ }
754
+ const nativeContainedChildren = /* @__PURE__ */ new WeakSet();
755
+ function markNativeContainedChild(child) {
756
+ nativeContainedChildren.add(child);
757
+ }
758
+ function isNativeContainedChild(child) {
759
+ return nativeContainedChildren.has(child);
760
+ }
761
+ const retainedWindowsExitHandles = /* @__PURE__ */ new WeakMap();
762
+ function retainWindowsProcessExitHandle(child) {
763
+ if (process.platform !== "win32" || !child.pid || child.exitCode !== null || child.signalCode !== null) return;
764
+ if (isNativeContainedChild(child) || retainedWindowsExitHandles.has(child)) return;
765
+ const hold = loadNativeHoldWindowsProcessExit();
766
+ if (hold === null) return;
767
+ try {
768
+ const handle = hold(child.pid);
769
+ if (handle !== null) retainedWindowsExitHandles.set(child, handle);
770
+ } catch {}
771
+ }
772
+ function releaseRetainedWindowsProcessExitHandle(child) {
773
+ const handle = retainedWindowsExitHandles.get(child);
774
+ if (handle === void 0) return;
775
+ retainedWindowsExitHandles.delete(child);
776
+ try {
777
+ handle.close();
778
+ } catch {}
779
+ }
780
+ function createChildProcessEnvironment(overrides, baseEnv = process.env) {
781
+ const callerChose = baseEnv !== process.env && baseEnv["ATOMIC_HOST_STORAGE_ADAPTERS"] !== process.env["ATOMIC_HOST_STORAGE_ADAPTERS"];
782
+ const env = {
783
+ ...baseEnv,
784
+ ...callerChose ? {} : hostStorageAdaptersEnvironment(),
785
+ ...overrides,
786
+ AI_AGENT: ATOMIC_AI_AGENT
787
+ };
788
+ applyDebugSettingToChildEnvironment(env);
789
+ return env;
790
+ }
791
+ const WINDOWS_SHELL_COMMANDS = /* @__PURE__ */ new Set([
792
+ "bun",
793
+ "npm",
794
+ "npx",
795
+ "pnpm",
796
+ "yarn",
797
+ "yarnpkg",
798
+ "corepack"
799
+ ]);
800
+ function shouldUseWindowsShell(command) {
801
+ if (process.platform !== "win32") return false;
802
+ const commandName = basename$1(command).toLowerCase();
803
+ return commandName.endsWith(".cmd") || commandName.endsWith(".bat") || WINDOWS_SHELL_COMMANDS.has(commandName);
804
+ }
805
+ function processLaunch(command, options = {}) {
806
+ return helperLaunch(command, {
807
+ ...launchSearch(options),
808
+ shellScripts: process.platform === "win32"
809
+ });
810
+ }
811
+ function processLaunchAsync(command, options = {}) {
812
+ return helperLaunchAsync(command, {
813
+ ...launchSearch(options),
814
+ shellScripts: process.platform === "win32"
815
+ });
816
+ }
817
+ function launchSearch(options) {
818
+ return {
819
+ env: options.env ? createChildProcessEnvironment(void 0, options.env) : createChildProcessEnvironment(),
820
+ ...options.cwd === void 0 ? {} : { cwd: options.cwd }
821
+ };
822
+ }
823
+ function spawnProcess(command, args, options) {
824
+ if (options.shell) return spawnChild(command, args, options);
825
+ return spawnLaunchedProcess(processLaunch(command, {
826
+ cwd: typeof options.cwd === "string" ? options.cwd : options.cwd?.pathname,
827
+ env: options.env
828
+ }), args, options);
829
+ }
830
+ function shellReadable(launch, shell) {
831
+ if (!shell || launch.missing !== void 0 || !isAbsolute$1(launch.file)) return launch;
832
+ return { file: process.platform === "win32" ? `"${launch.file}"` : `'${launch.file.replaceAll("'", `'\\''`)}'` };
833
+ }
834
+ function spawnLaunchedProcess(launch, args, options) {
835
+ if (launch.missing !== void 0) return spawn(launch.file, args, {
836
+ ...childEnvironment(options),
837
+ ...missingHelperOptions(launch)
838
+ });
839
+ return spawnChild(shellReadable(launch, options.shell).file, args, options);
840
+ }
841
+ function spawnChild(file, args, options) {
842
+ const childOptions = childEnvironment(options);
843
+ return process.platform === "win32" ? (0, import_cross_spawn.default)(file, args, childOptions) : spawn(file, args, childOptions);
844
+ }
845
+ function childEnvironment(options) {
846
+ return {
847
+ ...options,
848
+ env: options.env ? createChildProcessEnvironment(void 0, options.env) : createChildProcessEnvironment()
849
+ };
850
+ }
851
+ function spawnLaunchedProcessSync(launch, args, options) {
852
+ if (launch.missing !== void 0) return spawnSync(launch.file, args, {
853
+ ...childEnvironment(options),
854
+ ...missingHelperOptions(launch)
855
+ });
856
+ return spawnChildSync(shellReadable(launch, options.shell).file, args, options);
857
+ }
858
+ function spawnChildSync(file, args, options) {
859
+ const childOptions = childEnvironment(options);
860
+ return process.platform === "win32" ? import_cross_spawn.default.sync(file, args, childOptions) : spawnSync(file, args, childOptions);
861
+ }
862
+ function isWindowsProcessAlive(pid) {
863
+ try {
864
+ process.kill(pid, 0);
865
+ return true;
866
+ } catch (error) {
867
+ return error.code !== "ESRCH";
868
+ }
869
+ }
870
+ function mapSignalExitCode(code, signal, platform) {
871
+ if (code !== null || signal === null || platform === "win32") return code;
872
+ return 128 + (constants$1.signals[signal] ?? 0);
873
+ }
874
+ function waitForChildProcess(child, options = {}) {
875
+ return new Promise((resolve, reject) => {
876
+ let settled = false;
877
+ let exited = false;
878
+ let exitCode = null;
879
+ let postExitIdleTimer;
880
+ let postExitIdleFallback;
881
+ let postExitActiveDrainHardCapTimer;
882
+ let postExitActiveDrainHardCapFallback;
883
+ let stdoutEnded = child.stdout === null || child.stdout.readableEnded;
884
+ let stderrEnded = child.stderr === null || child.stderr.readableEnded;
885
+ let windowsExitPoll;
886
+ let windowsExitCodeGraceTimer;
887
+ let windowsExitCodeFallback;
888
+ const platform = options.platform ?? process.platform;
889
+ const processAlive = options.isWindowsProcessAlive ?? isWindowsProcessAlive;
890
+ const windowsExitPollIntervalMs = options.windowsExitPollIntervalMs ?? WINDOWS_EXIT_POLL_INTERVAL_MS;
891
+ const windowsExitCodeGraceMs = options.windowsExitCodeGraceMs ?? WINDOWS_EXIT_CODE_GRACE_MS;
892
+ const postExitIdleGraceMs = options.postExitIdleGraceMs ?? EXIT_STDIO_IDLE_GRACE_MS;
893
+ const claimedRetained = retainedWindowsExitHandles.get(child);
894
+ if (claimedRetained !== void 0) retainedWindowsExitHandles.delete(child);
895
+ let exitHandle = claimedRetained;
896
+ const closeExitHandle = () => {
897
+ if (exitHandle === void 0) return;
898
+ const handle = exitHandle;
899
+ exitHandle = void 0;
900
+ try {
901
+ handle.close();
902
+ } catch {}
903
+ };
904
+ const alreadyExited = child.pid !== void 0 && child.pid > 0 && (child.exitCode !== null || child.signalCode !== null);
905
+ const needsWindowsFallback = platform === "win32" && Boolean(child.pid) && !isNativeContainedChild(child);
906
+ if (alreadyExited || !needsWindowsFallback) closeExitHandle();
907
+ else if (exitHandle === void 0 && child.pid) {
908
+ if (options.holdWindowsProcessExit !== void 0) try {
909
+ exitHandle = options.holdWindowsProcessExit(child.pid) ?? void 0;
910
+ } catch {
911
+ exitHandle = void 0;
912
+ }
913
+ else if (options.isWindowsProcessAlive === void 0) {
914
+ const hold = loadNativeHoldWindowsProcessExit();
915
+ if (hold !== null) try {
916
+ exitHandle = hold(child.pid) ?? void 0;
917
+ } catch {
918
+ exitHandle = void 0;
919
+ }
920
+ }
921
+ }
922
+ const cleanup = () => {
923
+ if (windowsExitPoll) {
924
+ clearInterval(windowsExitPoll);
925
+ windowsExitPoll = void 0;
926
+ }
927
+ if (postExitIdleTimer) {
928
+ clearTimeout(postExitIdleTimer);
929
+ postExitIdleTimer = void 0;
930
+ }
931
+ if (postExitIdleFallback) {
932
+ clearImmediate(postExitIdleFallback);
933
+ postExitIdleFallback = void 0;
934
+ }
935
+ if (postExitActiveDrainHardCapTimer) {
936
+ clearTimeout(postExitActiveDrainHardCapTimer);
937
+ postExitActiveDrainHardCapTimer = void 0;
938
+ }
939
+ if (postExitActiveDrainHardCapFallback) {
940
+ clearImmediate(postExitActiveDrainHardCapFallback);
941
+ postExitActiveDrainHardCapFallback = void 0;
942
+ }
943
+ if (windowsExitCodeGraceTimer) {
944
+ clearTimeout(windowsExitCodeGraceTimer);
945
+ windowsExitCodeGraceTimer = void 0;
946
+ }
947
+ if (windowsExitCodeFallback) {
948
+ clearImmediate(windowsExitCodeFallback);
949
+ windowsExitCodeFallback = void 0;
950
+ }
951
+ closeExitHandle();
952
+ options.signal?.removeEventListener("abort", onAbort);
953
+ child.removeListener("error", onError);
954
+ child.removeListener("exit", onExit);
955
+ child.removeListener("close", onClose);
956
+ child.stdout?.removeListener("end", onStdoutEnd);
957
+ child.stderr?.removeListener("end", onStderrEnd);
958
+ child.stdout?.removeListener("data", onData);
959
+ child.stderr?.removeListener("data", onData);
960
+ };
961
+ const finalize = (code) => {
962
+ if (settled) return;
963
+ settled = true;
964
+ cleanup();
965
+ child.stdout?.destroy();
966
+ child.stderr?.destroy();
967
+ resolve(code);
968
+ };
969
+ const failUnknownExitStatus = () => {
970
+ if (settled) return;
971
+ settled = true;
972
+ cleanup();
973
+ child.stdout?.destroy();
974
+ child.stderr?.destroy();
975
+ reject(new ChildProcessExitStatusUnknownError(child.pid));
976
+ };
977
+ const maybeFinalizeAfterExit = () => {
978
+ if (!exited || settled) return;
979
+ if (stdoutEnded && stderrEnded) finalize(exitCode);
980
+ };
981
+ const armIdleTimer = () => {
982
+ if (postExitActiveDrainHardCapFallback) return;
983
+ if (postExitIdleTimer) clearTimeout(postExitIdleTimer);
984
+ if (postExitIdleFallback) {
985
+ clearImmediate(postExitIdleFallback);
986
+ postExitIdleFallback = void 0;
987
+ }
988
+ postExitIdleTimer = setTimeout(() => {
989
+ postExitIdleTimer = void 0;
990
+ postExitIdleFallback = setImmediate(() => {
991
+ postExitIdleFallback = void 0;
992
+ finalize(exitCode);
993
+ });
994
+ }, postExitIdleGraceMs);
995
+ };
996
+ const armActiveDrainHardCapTimer = () => {
997
+ if (postExitActiveDrainHardCapTimer || postExitActiveDrainHardCapFallback) return;
998
+ postExitActiveDrainHardCapTimer = setTimeout(() => {
999
+ postExitActiveDrainHardCapTimer = void 0;
1000
+ if (postExitIdleTimer) {
1001
+ clearTimeout(postExitIdleTimer);
1002
+ postExitIdleTimer = void 0;
1003
+ }
1004
+ if (postExitIdleFallback) {
1005
+ clearImmediate(postExitIdleFallback);
1006
+ postExitIdleFallback = void 0;
1007
+ }
1008
+ postExitActiveDrainHardCapFallback = setImmediate(() => {
1009
+ postExitActiveDrainHardCapFallback = void 0;
1010
+ finalize(exitCode);
1011
+ });
1012
+ }, EXIT_STDIO_ACTIVE_DRAIN_HARD_CAP_MS);
1013
+ };
1014
+ const onData = () => {
1015
+ if (exited && !settled) armIdleTimer();
1016
+ };
1017
+ const onStdoutEnd = () => {
1018
+ stdoutEnded = true;
1019
+ maybeFinalizeAfterExit();
1020
+ };
1021
+ const onStderrEnd = () => {
1022
+ stderrEnded = true;
1023
+ maybeFinalizeAfterExit();
1024
+ };
1025
+ const onError = (err) => {
1026
+ if (settled) return;
1027
+ settled = true;
1028
+ cleanup();
1029
+ reject(err);
1030
+ };
1031
+ const onExit = (code, signal) => {
1032
+ if (windowsExitPoll) {
1033
+ clearInterval(windowsExitPoll);
1034
+ windowsExitPoll = void 0;
1035
+ }
1036
+ if (windowsExitCodeGraceTimer) {
1037
+ clearTimeout(windowsExitCodeGraceTimer);
1038
+ windowsExitCodeGraceTimer = void 0;
1039
+ }
1040
+ if (windowsExitCodeFallback) {
1041
+ clearImmediate(windowsExitCodeFallback);
1042
+ windowsExitCodeFallback = void 0;
1043
+ }
1044
+ exited = true;
1045
+ exitCode = mapSignalExitCode(code, signal, platform);
1046
+ maybeFinalizeAfterExit();
1047
+ if (!settled) {
1048
+ armActiveDrainHardCapTimer();
1049
+ armIdleTimer();
1050
+ }
1051
+ };
1052
+ const resolveWindowsFallback = () => {
1053
+ if (exited || settled) return;
1054
+ if (child.exitCode !== null || child.signalCode !== null) {
1055
+ onExit(child.exitCode, child.signalCode);
1056
+ return;
1057
+ }
1058
+ if (exitHandle !== void 0) {
1059
+ let status;
1060
+ try {
1061
+ status = exitHandle.pollExit();
1062
+ } catch {
1063
+ status = void 0;
1064
+ }
1065
+ if (status?.exited && !status.unknown && status.exitCode !== void 0 && status.exitCode !== null) {
1066
+ onExit(status.exitCode, null);
1067
+ return;
1068
+ }
1069
+ closeExitHandle();
1070
+ if (!options.signal?.aborted) return;
1071
+ }
1072
+ failUnknownExitStatus();
1073
+ };
1074
+ const armWindowsExitCodeGraceTimer = () => {
1075
+ if (windowsExitCodeGraceTimer || windowsExitCodeFallback || exited || settled) return;
1076
+ if (windowsExitPoll) {
1077
+ clearInterval(windowsExitPoll);
1078
+ windowsExitPoll = void 0;
1079
+ }
1080
+ windowsExitCodeGraceTimer = setTimeout(() => {
1081
+ windowsExitCodeGraceTimer = void 0;
1082
+ windowsExitCodeFallback = setImmediate(() => {
1083
+ windowsExitCodeFallback = void 0;
1084
+ resolveWindowsFallback();
1085
+ });
1086
+ }, windowsExitCodeGraceMs);
1087
+ };
1088
+ const pollWindowsExit = () => {
1089
+ if (!needsWindowsFallback || !child.pid || exited || settled || windowsExitCodeGraceTimer || windowsExitCodeFallback) return;
1090
+ if (child.exitCode !== null || child.signalCode !== null) {
1091
+ onExit(child.exitCode, child.signalCode);
1092
+ return;
1093
+ }
1094
+ if (exitHandle !== void 0) {
1095
+ let status;
1096
+ try {
1097
+ status = exitHandle.pollExit();
1098
+ } catch {
1099
+ status = void 0;
1100
+ }
1101
+ if (status === void 0 || status.unknown) {
1102
+ closeExitHandle();
1103
+ if (options.signal?.aborted) {
1104
+ if (status?.exited || !processAlive(child.pid)) armWindowsExitCodeGraceTimer();
1105
+ } else if (windowsExitPoll) {
1106
+ clearInterval(windowsExitPoll);
1107
+ windowsExitPoll = void 0;
1108
+ }
1109
+ return;
1110
+ }
1111
+ if (status.exited) armWindowsExitCodeGraceTimer();
1112
+ return;
1113
+ }
1114
+ if (!options.signal?.aborted) return;
1115
+ if (!processAlive(child.pid)) armWindowsExitCodeGraceTimer();
1116
+ };
1117
+ const onAbort = () => {
1118
+ if (!needsWindowsFallback || exited || settled) return;
1119
+ if (exitHandle === void 0 && !windowsExitPoll && !windowsExitCodeGraceTimer && !windowsExitCodeFallback) windowsExitPoll = setInterval(pollWindowsExit, windowsExitPollIntervalMs);
1120
+ pollWindowsExit();
1121
+ };
1122
+ const onClose = (code, signal) => {
1123
+ finalize(mapSignalExitCode(code, signal, platform));
1124
+ };
1125
+ child.stdout?.once("end", onStdoutEnd);
1126
+ child.stderr?.once("end", onStderrEnd);
1127
+ child.stdout?.on("data", onData);
1128
+ child.stderr?.on("data", onData);
1129
+ child.once("error", onError);
1130
+ child.once("exit", onExit);
1131
+ child.once("close", onClose);
1132
+ if (alreadyExited) {
1133
+ onExit(child.exitCode, child.signalCode);
1134
+ return;
1135
+ }
1136
+ if (needsWindowsFallback) {
1137
+ if (exitHandle !== void 0) windowsExitPoll = setInterval(pollWindowsExit, windowsExitPollIntervalMs);
1138
+ if (options.signal !== void 0) {
1139
+ if (options.signal.aborted) onAbort();
1140
+ else options.signal.addEventListener("abort", onAbort, { once: true });
1141
+ }
1142
+ }
1143
+ });
1144
+ }
1145
+ // dist/utils/paths.js
1146
+ const UNICODE_SPACES = /[\u00A0\u2000-\u200A\u202F\u205F\u3000]/g;
1147
+ function getHomeDir() {
1148
+ if (process.platform === "win32") {
1149
+ if (process.env.USERPROFILE) return process.env.USERPROFILE;
1150
+ if (process.env.HOMEDRIVE && process.env.HOMEPATH) return `${process.env.HOMEDRIVE}${process.env.HOMEPATH}`;
1151
+ if (process.env.HOME) return process.env.HOME;
1152
+ return homedir();
1153
+ }
1154
+ return process.env.HOME || process.env.USERPROFILE || homedir();
1155
+ }
1156
+ /**
1157
+ * Returns true if the value is NOT a package source (npm:, git:, etc.)
1158
+ * or a remote URL protocol. Bare names, relative paths, and file: URLs
1159
+ * are considered local.
1160
+ */
1161
+ function isLocalPath(value) {
1162
+ const trimmed = value.trim();
1163
+ if (trimmed.startsWith("npm:") || trimmed.startsWith("git:") || trimmed.startsWith("github:") || trimmed.startsWith("http:") || trimmed.startsWith("https:") || trimmed.startsWith("ssh:") || trimmed.startsWith("builtin:")) return false;
1164
+ return true;
1165
+ }
1166
+ /** Convert Git Bash, MSYS, Cygwin, and WSL drive paths to a form native Windows APIs accept. */
1167
+ function normalizeWindowsShellPath(filePath) {
1168
+ if (!filePath.startsWith("/") || filePath.startsWith("//") || filePath.includes("\\")) return filePath;
1169
+ const match = filePath.match(/^\/(?:mnt\/|cygdrive\/)?([a-z])(?:\/(.*))?$/i);
1170
+ if (!match) return filePath;
1171
+ const suffix = match[2]?.replaceAll("/", "\\");
1172
+ return `${match[1].toUpperCase()}:\\${suffix ?? ""}`;
1173
+ }
1174
+ function normalizePath(input, options = {}) {
1175
+ let normalized = options.trim ? input.trim() : input;
1176
+ if (options.normalizeUnicodeSpaces) normalized = normalized.replace(UNICODE_SPACES, " ");
1177
+ if (options.stripAtPrefix && normalized.startsWith("@")) normalized = normalized.slice(1);
1178
+ if (process.platform === "win32") normalized = normalizeWindowsShellPath(normalized);
1179
+ if (options.expandTilde ?? true) {
1180
+ const home = options.homeDir ?? getHomeDir();
1181
+ if (normalized === "~") return home;
1182
+ if (normalized.startsWith("~/") || process.platform === "win32" && normalized.startsWith("~\\")) return join$1(home, normalized.slice(2));
1183
+ }
1184
+ if (/^file:\/\//.test(normalized)) return fileURLToPath(normalized);
1185
+ return normalized;
1186
+ }
1187
+ function resolvePath(input, baseDir = process.cwd(), options = {}) {
1188
+ const normalized = normalizePath(input, options);
1189
+ const normalizedBaseDir = normalizePath(baseDir);
1190
+ return isAbsolute$1(normalized) ? resolve$1(normalized) : resolve$1(normalizedBaseDir, normalized);
1191
+ }
1192
+ function getCwdRelativePath(filePath, cwd) {
1193
+ const resolvedCwd = resolvePath(cwd);
1194
+ const resolvedPath = resolvePath(filePath, resolvedCwd);
1195
+ const relativePath = relative$1(resolvedCwd, resolvedPath);
1196
+ return relativePath === "" || relativePath !== ".." && !relativePath.startsWith(`..${sep$1}`) && !isAbsolute$1(relativePath) ? relativePath || "." : void 0;
1197
+ }
1198
+ function formatPathRelativeToCwdOrAbsolute(filePath, cwd) {
1199
+ const absolutePath = resolvePath(filePath, cwd);
1200
+ return (getCwdRelativePath(absolutePath, cwd) ?? absolutePath).split(sep$1).join("/");
1201
+ }
1202
+ /**
1203
+ * Key for comparing filesystem paths: the resolved absolute path, case-folded on Windows because Windows
1204
+ * paths are case-insensitive (`c:\Users` and `C:\Users` are the same directory). NTFS can enable
1205
+ * per-directory case sensitivity, but it is rarely used outside WSL interop, so it is ignored here.
1206
+ * Does not touch the filesystem; resolve symlinks first when they must compare equal. Use only for
1207
+ * comparison, never for display or filesystem access.
1208
+ */
1209
+ function getPathComparisonKey(path) {
1210
+ const pathApi = getPlatformPathApi();
1211
+ const resolvedPath = pathApi.resolve(path);
1212
+ return pathApi === win32$1 ? resolvedPath.toLowerCase() : resolvedPath;
1213
+ }
1214
+ /** `node:path` rules for the current platform, read at call time so tests can simulate Windows. */
1215
+ function getPlatformPathApi() {
1216
+ return process.platform === "win32" ? win32$1 : posix;
1217
+ }
1218
+ /** True when both paths name the same location (see `getPathComparisonKey`). */
1219
+ function pathsEqual(left, right) {
1220
+ return getPathComparisonKey(left) === getPathComparisonKey(right);
1221
+ }
1222
+ /** True when `child` is `parent` or inside it (see `getPathComparisonKey`). */
1223
+ function isPathWithin(parent, child) {
1224
+ const parentKey = getPathComparisonKey(parent);
1225
+ const childKey = getPathComparisonKey(child);
1226
+ if (childKey === parentKey) return true;
1227
+ const pathSep = getPlatformPathApi().sep;
1228
+ return childKey.startsWith(parentKey.endsWith(pathSep) ? parentKey : `${parentKey}${pathSep}`);
1229
+ }
1230
+ /** Replace a leading home directory with `~` for display. Relative paths are returned unchanged. */
1231
+ function shortenHomePath(path, homeDir = homedir()) {
1232
+ const pathApi = getPlatformPathApi();
1233
+ if (!homeDir || !pathApi.isAbsolute(path) || !isPathWithin(homeDir, path)) return path;
1234
+ const relativePath = pathApi.relative(homeDir, path);
1235
+ return relativePath ? `~${pathApi.sep}${relativePath}` : "~";
1236
+ }
1237
+ async function markPathIgnoredByCloudSync(path) {
1238
+ const attrs = process.platform === "darwin" ? ["com.dropbox.ignored", "com.apple.fileprovider.ignore#P"] : process.platform === "linux" ? ["user.com.dropbox.ignored"] : [];
1239
+ for (const attr of attrs) {
1240
+ const [command, args] = process.platform === "darwin" ? ["xattr", [
1241
+ "-w",
1242
+ attr,
1243
+ "1",
1244
+ path
1245
+ ]] : ["setfattr", [
1246
+ "-n",
1247
+ attr,
1248
+ "-v",
1249
+ "1",
1250
+ path
1251
+ ]];
1252
+ try {
1253
+ await waitForChildProcess(spawnLaunchedProcess(await processLaunchAsync(command), args, { stdio: "ignore" }));
1254
+ } catch {}
1255
+ }
1256
+ }
1257
+ // dist/utils/split-launcher.js
1258
+ /**
1259
+ * Split-launcher / foreign-build `import.meta.url` handling.
1260
+ *
1261
+ * Atomic's release binaries use a split launcher: a tiny compiled `atomic` /
1262
+ * `atomic.exe` executable sets `ATOMIC_CODING_AGENT=true` and then dynamically
1263
+ * imports the bundled sidecar `app.js` (plus raw-TS built-in extensions) from
1264
+ * disk next to the executable.
1265
+ *
1266
+ * Unlike pi's single monolithic `bun --compile` binary — where `import.meta.url`
1267
+ * is always a `$bunfs://` virtual-FS URL — the split sidecar bundle carries the
1268
+ * build machine's source path baked in at bundle time (e.g. a macOS
1269
+ * `file:///Users/.../app.js` URL). On Windows, `fileURLToPath()` rejects that
1270
+ * URL with `ERR_INVALID_FILE_URL_PATH` ("File URL path must be an absolute
1271
+ * path") because `/Users/...` has no drive letter, so every site that decodes
1272
+ * `import.meta.url` to a filesystem path must tolerate it.
1273
+ *
1274
+ * These helpers centralize that tolerance: decode normally, and only when the
1275
+ * decode fails under the split launcher fall back to a path resolved relative to
1276
+ * the launcher executable (where the sidecar bundle and its assets actually
1277
+ * live). This mirrors pi's convention of a single detection point rather than
1278
+ * scattered ad-hoc guards.
1279
+ */
1280
+ function isSplitLauncherRuntime() {
1281
+ return process.env.ATOMIC_CODING_AGENT === "true" && /(?:^|[\\/])atomic(?:\.exe)?$/i.test(process.execPath);
1282
+ }
1283
+ /** Directory containing the launcher executable and its sidecar bundle/assets. */
1284
+ function splitLauncherDir() {
1285
+ return dirname$1(process.execPath);
1286
+ }
1287
+ /**
1288
+ * Resolve a module's directory from its `import.meta.url`, tolerating the
1289
+ * split-launcher case where the bundled URL is a foreign-OS build path.
1290
+ * `execRelativeSegments` locate the equivalent directory next to the launcher.
1291
+ */
1292
+ function moduleDirFromMetaUrl(metaUrl, ...execRelativeSegments) {
1293
+ try {
1294
+ return dirname$1(fileURLToPath(metaUrl));
1295
+ } catch (error) {
1296
+ if (isSplitLauncherRuntime()) return join$1(splitLauncherDir(), ...execRelativeSegments);
1297
+ throw error;
1298
+ }
1299
+ }
1300
+ /**
1301
+ * Resolve a module's filename from its `import.meta.url`, tolerating the
1302
+ * split-launcher case. `execRelativeFile` locates the equivalent file next to
1303
+ * the launcher (used as a stable resolution base, e.g. for `createRequire`).
1304
+ */
1305
+ function moduleFileFromMetaUrl(metaUrl, execRelativeFile) {
1306
+ try {
1307
+ return fileURLToPath(metaUrl);
1308
+ } catch (error) {
1309
+ if (isSplitLauncherRuntime()) return join$1(splitLauncherDir(), execRelativeFile);
1310
+ throw error;
1311
+ }
1312
+ }
1313
+ // dist/config-self-update.js
1314
+ function normalizeSelfUpdateTarget(target) {
1315
+ if (typeof target === "string") return {
1316
+ packageName: target,
1317
+ installSpec: target
1318
+ };
1319
+ return {
1320
+ packageName: target.packageName,
1321
+ installSpec: target.installSpec ?? target.packageName
1322
+ };
1323
+ }
1324
+ function makeSelfUpdateCommand(installStep, uninstallStep) {
1325
+ if (!uninstallStep) return installStep;
1326
+ return {
1327
+ ...installStep,
1328
+ display: `${uninstallStep.display} && ${installStep.display}`,
1329
+ steps: [uninstallStep, installStep]
1330
+ };
1331
+ }
1332
+ function makeSelfUpdateCommandStep(command, args) {
1333
+ return {
1334
+ command,
1335
+ args,
1336
+ display: [command, ...args].map((arg) => /\s/.test(arg) ? `"${arg}"` : arg).join(" ")
1337
+ };
1338
+ }
1339
+ function detectInstallMethodForRuntime(runtime) {
1340
+ if (runtime.isBunBinary) return "bun-binary";
1341
+ const resolvedPath = `${runtime.moduleDir}\0${process.execPath || ""}`.toLowerCase().replace(/\\/g, "/");
1342
+ if (resolvedPath.includes("/pnpm/") || resolvedPath.includes("/.pnpm/")) return "pnpm";
1343
+ if (resolvedPath.includes("/yarn/") || resolvedPath.includes("/.yarn/")) return "yarn";
1344
+ if (resolvedPath.includes("/install/global/node_modules/")) return "bun";
1345
+ if (resolvedPath.includes("/npm/") || resolvedPath.includes("/node_modules/")) return "npm";
1346
+ return "unknown";
1347
+ }
1348
+ function getInferredNpmInstall(runtime) {
1349
+ const packageDir = runtime.getPackageDir();
1350
+ const path = process.platform === "win32" || packageDir.includes("\\") ? win32 : {
1351
+ basename,
1352
+ dirname
1353
+ };
1354
+ const parent = path.dirname(packageDir);
1355
+ let root;
1356
+ if (path.basename(parent).startsWith("@") && path.basename(path.dirname(parent)) === "node_modules") root = path.dirname(parent);
1357
+ else if (path.basename(parent) === "node_modules") root = parent;
1358
+ if (!root) return void 0;
1359
+ const rootParent = path.dirname(root);
1360
+ if (path.basename(rootParent) === "lib") return {
1361
+ root,
1362
+ prefix: path.dirname(rootParent)
1363
+ };
1364
+ }
1365
+ function getSelfUpdateCommandForMethod(runtime, method, installedPackageName, updatePackageName = installedPackageName, npmCommand, installSpec = updatePackageName) {
1366
+ switch (method) {
1367
+ case "bun-binary": return;
1368
+ case "pnpm": {
1369
+ const match = readCommandOutput("pnpm", ["root", "-g"]) ? void 0 : /^(.*[\\/]global[\\/][^\\/]+)[\\/]\.pnpm[\\/]/.exec(runtime.getPackageDir());
1370
+ const binDirArgs = match ? [`--config.global-bin-dir=${process.env.PNPM_HOME || dirname(dirname(match[1]))}`] : [];
1371
+ return makeSelfUpdateCommand(makeSelfUpdateCommandStep("pnpm", [
1372
+ "install",
1373
+ "-g",
1374
+ "--ignore-scripts",
1375
+ "--config.minimumReleaseAge=0",
1376
+ ...binDirArgs,
1377
+ installSpec
1378
+ ]), updatePackageName === installedPackageName ? void 0 : makeSelfUpdateCommandStep("pnpm", [
1379
+ "remove",
1380
+ "-g",
1381
+ ...binDirArgs,
1382
+ installedPackageName
1383
+ ]));
1384
+ }
1385
+ case "yarn": return makeSelfUpdateCommand(makeSelfUpdateCommandStep("yarn", [
1386
+ "global",
1387
+ "add",
1388
+ "--ignore-scripts",
1389
+ installSpec
1390
+ ]), updatePackageName === installedPackageName ? void 0 : makeSelfUpdateCommandStep("yarn", [
1391
+ "global",
1392
+ "remove",
1393
+ installedPackageName
1394
+ ]));
1395
+ case "bun": return makeSelfUpdateCommand(makeSelfUpdateCommandStep("bun", [
1396
+ "install",
1397
+ "-g",
1398
+ "--ignore-scripts",
1399
+ "--minimum-release-age=0",
1400
+ installSpec
1401
+ ]), updatePackageName === installedPackageName ? void 0 : makeSelfUpdateCommandStep("bun", [
1402
+ "uninstall",
1403
+ "-g",
1404
+ installedPackageName
1405
+ ]));
1406
+ case "npm": {
1407
+ const [command = "npm", ...npmArgs] = npmCommand ?? [];
1408
+ const inferred = npmCommand?.length ? void 0 : getInferredNpmInstall(runtime);
1409
+ const prefixArgs = [...npmArgs, ...inferred ? ["--prefix", inferred.prefix] : []];
1410
+ return makeSelfUpdateCommand(makeSelfUpdateCommandStep(command, [
1411
+ ...prefixArgs,
1412
+ "install",
1413
+ "-g",
1414
+ "--ignore-scripts",
1415
+ "--min-release-age=0",
1416
+ installSpec
1417
+ ]), updatePackageName === installedPackageName ? void 0 : makeSelfUpdateCommandStep(command, [
1418
+ ...prefixArgs,
1419
+ "uninstall",
1420
+ "-g",
1421
+ installedPackageName
1422
+ ]));
1423
+ }
1424
+ case "unknown": return;
1425
+ }
1426
+ }
1427
+ function readCommandOutput(command, args, options = {}) {
1428
+ const result = spawnLaunchedProcessSync(processLaunch(command, { env: process.env }), args, {
1429
+ encoding: "utf-8",
1430
+ stdio: [
1431
+ "ignore",
1432
+ "pipe",
1433
+ "pipe"
1434
+ ],
1435
+ env: process.env,
1436
+ shell: shouldUseWindowsShell(command)
1437
+ });
1438
+ if (result.status === 0) return result.stdout.trim() || void 0;
1439
+ if (options.requireSuccess) {
1440
+ const reason = result.error?.message || result.stderr.trim() || `exit code ${result.status ?? "unknown"}`;
1441
+ throw new Error(`Failed to run ${[command, ...args].join(" ")}: ${reason}`);
1442
+ }
1443
+ }
1444
+ function getGlobalPackageRoots(runtime, method, _packageName, npmCommand) {
1445
+ switch (method) {
1446
+ case "npm": {
1447
+ const configured = !!npmCommand?.length;
1448
+ const [command = "npm", ...npmArgs] = npmCommand ?? [];
1449
+ if (configured && command === "bun") {
1450
+ const bunBin = readCommandOutput(command, [
1451
+ ...npmArgs,
1452
+ "pm",
1453
+ "bin",
1454
+ "-g"
1455
+ ], { requireSuccess: true });
1456
+ const roots = [join(homedir$1(), ".bun", "install", "global", "node_modules")];
1457
+ if (bunBin) roots.push(join(dirname(bunBin), "install", "global", "node_modules"));
1458
+ return roots;
1459
+ }
1460
+ return [readCommandOutput(command, [
1461
+ ...npmArgs,
1462
+ "root",
1463
+ "-g"
1464
+ ], { requireSuccess: configured }), (configured ? void 0 : getInferredNpmInstall(runtime))?.root].filter((x) => !!x);
1465
+ }
1466
+ case "pnpm": {
1467
+ const root = readCommandOutput("pnpm", ["root", "-g"]);
1468
+ if (root) return [root, dirname(root)];
1469
+ const match = /^(.*[\\/]global[\\/][^\\/]+)[\\/]\.pnpm[\\/]/.exec(runtime.getPackageDir());
1470
+ return match ? [match[1]] : [];
1471
+ }
1472
+ case "yarn": {
1473
+ const dir = readCommandOutput("yarn", ["global", "dir"]);
1474
+ return dir ? [dir, join(dir, "node_modules")] : [];
1475
+ }
1476
+ case "bun": {
1477
+ const bunBin = readCommandOutput("bun", [
1478
+ "pm",
1479
+ "bin",
1480
+ "-g"
1481
+ ]);
1482
+ const roots = [join(homedir$1(), ".bun", "install", "global", "node_modules")];
1483
+ if (bunBin) roots.push(join(dirname(bunBin), "install", "global", "node_modules"));
1484
+ return roots;
1485
+ }
1486
+ case "bun-binary":
1487
+ case "unknown": return [];
1488
+ }
1489
+ }
1490
+ function normalizeExistingPathForComparison(path, resolveSymlinks) {
1491
+ const resolvedPath = resolve(path);
1492
+ if (!existsSync(resolvedPath)) return;
1493
+ let normalizedPath = resolvedPath;
1494
+ if (resolveSymlinks) try {
1495
+ normalizedPath = realpathSync(resolvedPath);
1496
+ } catch {
1497
+ return;
1498
+ }
1499
+ if (process.platform === "win32") normalizedPath = normalizedPath.toLowerCase();
1500
+ return normalizedPath;
1501
+ }
1502
+ function getPathComparisonCandidates(path) {
1503
+ return Array.from(new Set([normalizeExistingPathForComparison(path, false), normalizeExistingPathForComparison(path, true)].filter((candidate) => !!candidate)));
1504
+ }
1505
+ function getEntrypointPackageDir() {
1506
+ const entrypoint = process.argv[1];
1507
+ if (!entrypoint) return void 0;
1508
+ let dir = dirname(entrypoint);
1509
+ while (dir !== dirname(dir)) {
1510
+ if (existsSync(join(dir, "package.json"))) return dir;
1511
+ dir = dirname(dir);
1512
+ }
1513
+ }
1514
+ function isSelfUpdatePathWritable(runtime) {
1515
+ const packageDir = runtime.getPackageDir();
1516
+ try {
1517
+ accessSync(packageDir, constants.W_OK);
1518
+ accessSync(dirname(packageDir), constants.W_OK);
1519
+ return true;
1520
+ } catch {
1521
+ return false;
1522
+ }
1523
+ }
1524
+ function isManagedByGlobalPackageManager(runtime, method, packageName, npmCommand) {
1525
+ const packageDirCandidates = [runtime.getPackageDir(), getEntrypointPackageDir()].filter((dir) => !!dir).flatMap((dir) => getPathComparisonCandidates(dir));
1526
+ return getGlobalPackageRoots(runtime, method, packageName, npmCommand).some((root) => {
1527
+ return getPathComparisonCandidates(root).some((normalizedRoot) => {
1528
+ const rootPrefix = normalizedRoot.endsWith(sep) ? normalizedRoot : `${normalizedRoot}${sep}`;
1529
+ return packageDirCandidates.some((packageDir) => packageDir.startsWith(rootPrefix));
1530
+ });
1531
+ });
1532
+ }
1533
+ function getSelfUpdateCommandForRuntime(runtime, packageName, npmCommand, updateTarget = packageName) {
1534
+ const method = detectInstallMethodForRuntime(runtime);
1535
+ const target = normalizeSelfUpdateTarget(updateTarget);
1536
+ const command = getSelfUpdateCommandForMethod(runtime, method, packageName, target.packageName, npmCommand, target.installSpec);
1537
+ if (!command || !isManagedByGlobalPackageManager(runtime, method, packageName, npmCommand) || !isSelfUpdatePathWritable(runtime)) return;
1538
+ return command;
1539
+ }
1540
+ function getSelfUpdateUnavailableInstructionForRuntime(runtime, packageName, npmCommand, updateTarget = packageName) {
1541
+ const method = detectInstallMethodForRuntime(runtime);
1542
+ if (method === "bun-binary") return `Download from: https://github.com/bastani-inc/atomic/releases/latest`;
1543
+ const target = normalizeSelfUpdateTarget(updateTarget);
1544
+ const command = getSelfUpdateCommandForMethod(runtime, method, packageName, target.packageName, npmCommand, target.installSpec);
1545
+ if (command && isManagedByGlobalPackageManager(runtime, method, packageName, npmCommand) && !isSelfUpdatePathWritable(runtime)) return `This installation is managed by a global ${method} install, but the install path is not writable. Update it yourself with: ${command.display}`;
1546
+ return `Update ${target.installSpec} using the package manager, wrapper, or source checkout that provides this installation.`;
1547
+ }
1548
+ function getUpdateInstructionForRuntime(runtime, packageName) {
1549
+ const command = getSelfUpdateCommandForMethod(runtime, detectInstallMethodForRuntime(runtime), packageName);
1550
+ if (command) return `Run: ${command.display}`;
1551
+ return getSelfUpdateUnavailableInstructionForRuntime(runtime, packageName);
1552
+ }
1553
+ // dist/config.js
1554
+ const __atomicDistModuleUrl$3 = new URL("../config.js", import.meta.url).href;
1555
+ const __filename = moduleFileFromMetaUrl(__atomicDistModuleUrl$3, "app.js");
1556
+ const __dirname = dirname(__filename);
1557
+ const bunFsMarkers = [
1558
+ "$bunfs",
1559
+ "~BUN",
1560
+ "%7EBUN"
1561
+ ];
1562
+ const isBunBinary = isSplitLauncherRuntime() || [__atomicDistModuleUrl$3, process.argv[1] ?? ""].some((candidate) => bunFsMarkers.some((marker) => candidate.includes(marker)));
1563
+ const isBundledBuild = process.env.ATOMIC_BUNDLED_BUILD === "1";
1564
+ const isBunRuntime = !!process.versions.bun;
1565
+ const modulePackageDir = isBunBinary ? void 0 : resolvePackageDirFrom(__dirname);
1566
+ function selfUpdateRuntime() {
1567
+ return {
1568
+ isBunBinary,
1569
+ isBunRuntime,
1570
+ moduleDir: __dirname,
1571
+ getPackageDir
1572
+ };
1573
+ }
1574
+ function detectInstallMethod() {
1575
+ return detectInstallMethodForRuntime(selfUpdateRuntime());
1576
+ }
1577
+ function getSelfUpdateCommand(packageName, npmCommand, updateTarget = {
1578
+ packageName,
1579
+ installSpec: packageName
1580
+ }) {
1581
+ return getSelfUpdateCommandForRuntime(selfUpdateRuntime(), packageName, npmCommand, updateTarget);
1582
+ }
1583
+ function getSelfUpdateUnavailableInstruction(packageName, npmCommand, updateTarget = {
1584
+ packageName,
1585
+ installSpec: packageName
1586
+ }) {
1587
+ return getSelfUpdateUnavailableInstructionForRuntime(selfUpdateRuntime(), packageName, npmCommand, updateTarget);
1588
+ }
1589
+ function getConfiguredSelfUpdateArgv(setting) {
1590
+ const fromEnv = getEnvValue(ENV_SELF_UPDATE_COMMAND)?.trim().split(/\s+/).filter(Boolean);
1591
+ if (fromEnv?.length) return fromEnv;
1592
+ return setting?.length ? setting : void 0;
1593
+ }
1594
+ function makeConfiguredSelfUpdateCommand(argv, release) {
1595
+ const values = {
1596
+ packageName: release.packageName,
1597
+ version: release.version,
1598
+ installSpec: `${release.packageName}@${release.version}`
1599
+ };
1600
+ const [command = "", ...args] = argv.map((arg) => arg.replace(/\{(packageName|version|installSpec)\}/g, (_, name) => values[name]));
1601
+ return makeSelfUpdateCommandStep(command, args);
1602
+ }
1603
+ function getUpdateInstruction(packageName) {
1604
+ return getUpdateInstructionForRuntime(selfUpdateRuntime(), packageName);
1605
+ }
1606
+ function getPackageDir() {
1607
+ const envDir = process.env.ATOMIC_PACKAGE_DIR ?? process.env.PI_PACKAGE_DIR;
1608
+ if (envDir) return normalizePath(envDir);
1609
+ if (isBunBinary || modulePackageDir === void 0) return dirname(process.execPath);
1610
+ return modulePackageDir;
1611
+ }
1612
+ function getModuleAssetRoot() {
1613
+ const hasPackageDirOverride = !!(process.env.ATOMIC_PACKAGE_DIR || process.env.PI_PACKAGE_DIR);
1614
+ if (!isBundledBuild && !hasPackageDirOverride) return __dirname;
1615
+ const packageDir = getPackageDir();
1616
+ return packageAssetRoots.get(packageDir) ?? findPackageAssetRoot(packageDir);
1617
+ }
1618
+ async function getModuleAssetRootAsync() {
1619
+ const hasPackageDirOverride = !!(process.env.ATOMIC_PACKAGE_DIR || process.env.PI_PACKAGE_DIR);
1620
+ if (!isBundledBuild && !hasPackageDirOverride) return __dirname;
1621
+ const packageDir = getPackageDir();
1622
+ const known = packageAssetRoots.get(packageDir);
1623
+ if (known !== void 0) return known;
1624
+ const root = join(packageDir, await pathExists(join(packageDir, "src")) ? "src" : "dist");
1625
+ packageAssetRoots.set(packageDir, root);
1626
+ return root;
1627
+ }
1628
+ const packageAssetRoots = /* @__PURE__ */ new Map();
1629
+ function findPackageAssetRoot(packageDir) {
1630
+ const root = join(packageDir, existsSync(join(packageDir, "src")) ? "src" : "dist");
1631
+ packageAssetRoots.set(packageDir, root);
1632
+ return root;
1633
+ }
1634
+ if (isBundledBuild || process.env.ATOMIC_PACKAGE_DIR || process.env.PI_PACKAGE_DIR) findPackageAssetRoot(getPackageDir());
1635
+ let codemodeWorkerDataUrl;
1636
+ let quickJSWasmPath;
1637
+ function getCodemodeWorkerUrl() {
1638
+ if (codemodeWorkerDataUrl) return codemodeWorkerDataUrl;
1639
+ const worker = isBunBinary ? join(getPackageDir(), "codemode-worker.js") : isBundledBuild ? join(dirname(resolve(process.argv[1])), "codemode-worker.js") : join(getModuleAssetRoot(), "codemode-worker.js");
1640
+ if (!isBunBinary && !isBundledBuild && !existsSync(worker)) return void 0;
1641
+ codemodeWorkerDataUrl ??= new URL(`data:text/javascript;base64,${readFileSync(worker).toString("base64")}`);
1642
+ return codemodeWorkerDataUrl;
1643
+ }
1644
+ async function getCodemodeWorkerUrlAsync() {
1645
+ if (codemodeWorkerDataUrl) return codemodeWorkerDataUrl;
1646
+ const worker = isBunBinary ? join(getPackageDir(), "codemode-worker.js") : isBundledBuild ? join(dirname(resolve(process.argv[1])), "codemode-worker.js") : join(await getModuleAssetRootAsync(), "codemode-worker.js");
1647
+ if (!isBunBinary && !isBundledBuild && !await pathExists(worker)) return void 0;
1648
+ const content = await readFile(worker);
1649
+ codemodeWorkerDataUrl ??= new URL(`data:text/javascript;base64,${content.toString("base64")}`);
1650
+ return codemodeWorkerDataUrl;
1651
+ }
1652
+ function getQuickJSWasmPath() {
1653
+ quickJSWasmPath ??= isBunBinary ? join(getPackageDir(), "quickjs.wasm") : isBundledBuild ? join(dirname(resolve(process.argv[1])), "quickjs.wasm") : createRequire(__filename).resolve("quickjs-wasi/quickjs.wasm");
1654
+ return quickJSWasmPath;
1655
+ }
1656
+ function detectInstallChange(packageJsonPath = startupPackageJsonPath) {
1657
+ if (isBunBinary || !packageJsonPath) return void 0;
1658
+ let installed;
1659
+ try {
1660
+ installed = JSON.parse(stripBom(readFileSync(packageJsonPath, "utf-8")));
1661
+ } catch (error) {
1662
+ return error.code === "ENOENT" ? { kind: "removed" } : void 0;
1663
+ }
1664
+ return installChangeOf(installed);
1665
+ }
1666
+ async function detectInstallChangeAsync(packageJsonPath = startupPackageJsonPath) {
1667
+ if (isBunBinary || !packageJsonPath) return void 0;
1668
+ let installed;
1669
+ try {
1670
+ installed = JSON.parse(stripBom(await readFile(packageJsonPath, "utf-8")));
1671
+ } catch (error) {
1672
+ return error.code === "ENOENT" ? { kind: "removed" } : void 0;
1673
+ }
1674
+ return installChangeOf(installed);
1675
+ }
1676
+ function installChangeOf(installed) {
1677
+ return installed.version && installed.version !== VERSION ? {
1678
+ kind: "updated",
1679
+ version: installed.version
1680
+ } : void 0;
1681
+ }
1682
+ function getThemesDir() {
1683
+ if (isBunBinary) return join(getPackageDir(), "theme");
1684
+ return join(getModuleAssetRoot(), "modes", "interactive", "theme");
1685
+ }
1686
+ function getExportTemplateDir() {
1687
+ if (isBunBinary) return join(getPackageDir(), "export-html");
1688
+ return join(getModuleAssetRoot(), "core", "export-html");
1689
+ }
1690
+ async function getExportTemplateDirAsync() {
1691
+ if (isBunBinary) return join(getPackageDir(), "export-html");
1692
+ return join(await getModuleAssetRootAsync(), "core", "export-html");
1693
+ }
1694
+ function getPackageJsonPath() {
1695
+ return join(getPackageDir(), "package.json");
1696
+ }
1697
+ function getReadmePath() {
1698
+ return resolve(join(getPackageDir(), "README.md"));
1699
+ }
1700
+ function getDocsPath() {
1701
+ return resolve(join(getPackageDir(), "docs"));
1702
+ }
1703
+ function getExamplesPath() {
1704
+ return resolve(join(getPackageDir(), "examples"));
1705
+ }
1706
+ function getChangelogPath() {
1707
+ return resolve(join(getPackageDir(), "CHANGELOG.md"));
1708
+ }
1709
+ function getInteractiveAssetsDir() {
1710
+ if (isBunBinary) return join(getPackageDir(), "assets");
1711
+ return join(getModuleAssetRoot(), "modes", "interactive", "assets");
1712
+ }
1713
+ function getBundledInteractiveAssetPath(name) {
1714
+ return join(getInteractiveAssetsDir(), name);
1715
+ }
1716
+ async function getBundledInteractiveAssetPathAsync(name) {
1717
+ const assetsDir = isBunBinary ? join(getPackageDir(), "assets") : join(await getModuleAssetRootAsync(), "modes", "interactive", "assets");
1718
+ return join(assetsDir, name);
1719
+ }
1720
+ let pkg = {};
1721
+ let startupPackageJsonPath;
1722
+ try {
1723
+ const packageJsonPath = getPackageJsonPath();
1724
+ pkg = JSON.parse(stripBom(readFileSync(packageJsonPath, "utf-8")));
1725
+ startupPackageJsonPath = packageJsonPath;
1726
+ } catch (e) {
1727
+ if (e.code !== "ENOENT") throw e;
1728
+ }
1729
+ function appNameFromPackageName(packageName) {
1730
+ const localName = packageName?.split("/").pop()?.trim();
1731
+ return localName && localName.length > 0 ? localName : void 0;
1732
+ }
1733
+ function readAppConfig(packageJson, appName) {
1734
+ if (appName) {
1735
+ const appConfig2 = packageJson[`${appName}Config`];
1736
+ if (appConfig2 && typeof appConfig2 === "object" && !Array.isArray(appConfig2)) return appConfig2;
1737
+ }
1738
+ return packageJson.piConfig;
1739
+ }
1740
+ const PACKAGE_NAME = pkg.name || "@bastani/atomic";
1741
+ const packageAppName = appNameFromPackageName(PACKAGE_NAME);
1742
+ const appConfig = readAppConfig(pkg, packageAppName);
1743
+ const APP_NAME = appConfig?.name || packageAppName || "pi";
1744
+ const APP_TITLE = appConfig?.name !== void 0 || APP_NAME !== "pi" ? APP_NAME : "π";
1745
+ const CONFIG_DIR_NAME = appConfig?.configDir || (APP_NAME === "pi" ? ".pi" : `.${APP_NAME}`);
1746
+ const LEGACY_CONFIG_DIR_NAME = ".pi";
1747
+ const CONFIG_DIR_NAMES = CONFIG_DIR_NAME === ".pi" ? [CONFIG_DIR_NAME] : [CONFIG_DIR_NAME, ".pi"];
1748
+ const VERSION = pkg.version || "0.0.0";
1749
+ const NATIVES_VERSION = exactRelease(pkg.dependencies?.["@bastani/atomic-natives"]);
1750
+ function exactRelease(range) {
1751
+ return typeof range === "string" && /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(range) ? range : void 0;
1752
+ }
1753
+ const CHANGELOG_URL = appConfig?.changelogUrl?.trim() || void 0;
1754
+ const ENV_PREFIX = APP_NAME.toUpperCase();
1755
+ const LEGACY_ENV_PREFIX = "PI";
1756
+ const ENV_AGENT_DIR = `${ENV_PREFIX}_CODING_AGENT_DIR`;
1757
+ const ENV_SESSION_DIR = `${ENV_PREFIX}_CODING_AGENT_SESSION_DIR`;
1758
+ const ENV_PACKAGE_DIR = `${ENV_PREFIX}_PACKAGE_DIR`;
1759
+ const ENV_OFFLINE = `${ENV_PREFIX}_OFFLINE`;
1760
+ const ENV_SKIP_VERSION_CHECK = `${ENV_PREFIX}_SKIP_VERSION_CHECK`;
1761
+ const ENV_STARTUP_BENCHMARK = `${ENV_PREFIX}_STARTUP_BENCHMARK`;
1762
+ const ENV_TELEMETRY = `${ENV_PREFIX}_TELEMETRY`;
1763
+ const ENV_SHARE_VIEWER_URL = `${ENV_PREFIX}_SHARE_VIEWER_URL`;
1764
+ const ENV_MODEL_CATALOG_URL = `${ENV_PREFIX}_MODEL_CATALOG_URL`;
1765
+ const ENV_CLEAR_ON_SHRINK = `${ENV_PREFIX}_CLEAR_ON_SHRINK`;
1766
+ const ENV_HARDWARE_CURSOR = `${ENV_PREFIX}_HARDWARE_CURSOR`;
1767
+ const ENV_CLIPBOARD_OSC52 = `${ENV_PREFIX}_CLIPBOARD_OSC52`;
1768
+ const ENV_TIMING = `${ENV_PREFIX}_TIMING`;
1769
+ const ENV_HEAP_MB = `${ENV_PREFIX}_HEAP_MB`;
1770
+ const ENV_CODEMODE_MAX_WORKERS = `${ENV_PREFIX}_CODEMODE_MAX_WORKERS`;
1771
+ const ENV_SELF_UPDATE_COMMAND = `${ENV_PREFIX}_SELF_UPDATE_COMMAND`;
1772
+ const ENV_STDIN_TIMEOUT_MS = `${ENV_PREFIX}_STDIN_TIMEOUT_MS`;
1773
+ const ENV_DEBUG = `${ENV_PREFIX}_DEBUG`;
1774
+ function getEnvNames(name) {
1775
+ if (ENV_PREFIX === "PI" || !name.startsWith(`${ENV_PREFIX}_`)) return [name];
1776
+ return [name, `PI_${name.slice(ENV_PREFIX.length + 1)}`];
1777
+ }
1778
+ function getEnvValue(name) {
1779
+ for (const candidate of getEnvNames(name)) {
1780
+ const value = process.env[candidate];
1781
+ if (value !== void 0) return value;
1782
+ }
1783
+ }
1784
+ function hasEnvValue(name) {
1785
+ return getEnvValue(name) !== void 0;
1786
+ }
1787
+ function setEnvValue(name, value) {
1788
+ process.env[name] = value;
1789
+ }
1790
+ function expandTildePath(path) {
1791
+ return normalizePath(path);
1792
+ }
1793
+ const DEFAULT_SHARE_VIEWER_URL = "https://bastani.ai/session/";
1794
+ const VERSION_ADOPTION_ENDPOINT = "https://atomic-version-adoption.bastani-atomic.workers.dev/v1/version-adoption";
1795
+ function getShareViewerUrl(gistId) {
1796
+ return `${getEnvValue(ENV_SHARE_VIEWER_URL) || DEFAULT_SHARE_VIEWER_URL}#${gistId}`;
1797
+ }
1798
+ function getAgentDir() {
1799
+ const envDir = getEnvValue(ENV_AGENT_DIR);
1800
+ if (envDir) return expandTildePath(envDir);
1801
+ return join(getHomeDir(), CONFIG_DIR_NAME, "agent");
1802
+ }
1803
+ function getLegacyAgentDir() {
1804
+ return join(getHomeDir(), ".pi", "agent");
1805
+ }
1806
+ function getAgentDirs() {
1807
+ const primary = getAgentDir();
1808
+ if (hasEnvValue(ENV_AGENT_DIR) || CONFIG_DIR_NAME === ".pi") return [primary];
1809
+ const legacy = getLegacyAgentDir();
1810
+ return legacy === primary ? [primary] : [primary, legacy];
1811
+ }
1812
+ function getUserConfigDirs() {
1813
+ return CONFIG_DIR_NAMES.map((name) => join(getHomeDir(), name));
1814
+ }
1815
+ function getProjectConfigDirs(cwd) {
1816
+ return CONFIG_DIR_NAMES.map((name) => join(cwd, name));
1817
+ }
1818
+ function getUserConfigPaths(...segments) {
1819
+ return getUserConfigDirs().map((dir) => join(dir, ...segments));
1820
+ }
1821
+ function getAgentConfigPaths(...segments) {
1822
+ return getAgentDirs().map((dir) => join(dir, ...segments));
1823
+ }
1824
+ function getProjectConfigPaths(cwd, ...segments) {
1825
+ return getProjectConfigDirs(cwd).map((dir) => join(dir, ...segments));
1826
+ }
1827
+ function getModelsConfigPaths(cwd, agentDir = getAgentDir(), includeProject = true) {
1828
+ const globalPaths = agentDir === getAgentDir() ? getAgentConfigPaths("models.json") : [join(agentDir, "models.json")];
1829
+ if (!includeProject) return globalPaths;
1830
+ const projectPaths = getProjectConfigPaths(cwd, "models.json");
1831
+ const paths = [];
1832
+ for (let index = 0; index < Math.max(projectPaths.length, globalPaths.length); index++) {
1833
+ if (projectPaths[index]) paths.push(projectPaths[index]);
1834
+ if (globalPaths[index]) paths.push(globalPaths[index]);
1835
+ }
1836
+ return [...new Set(paths)];
1837
+ }
1838
+ function getCustomThemesDir() {
1839
+ return join(getAgentDir(), "themes");
1840
+ }
1841
+ function getModelsPath() {
1842
+ return join(getAgentDir(), "models.json");
1843
+ }
1844
+ function getAuthPath() {
1845
+ return join(getAgentDir(), "auth.json");
1846
+ }
1847
+ function getSettingsPath() {
1848
+ return join(getAgentDir(), "settings.json");
1849
+ }
1850
+ function getToolsDir() {
1851
+ return join(getAgentDir(), "tools");
1852
+ }
1853
+ function getBinDir() {
1854
+ return join(getAgentDir(), "bin");
1855
+ }
1856
+ const BLUEPRINT_FILE_NAME = "blueprint.yaml";
1857
+ function getGlobalBlueprintPath(agentDir = getAgentDir()) {
1858
+ return join(agentDir, BLUEPRINT_FILE_NAME);
1859
+ }
1860
+ function getProjectBlueprintPath(dir) {
1861
+ return join(dir, CONFIG_DIR_NAME, BLUEPRINT_FILE_NAME);
1862
+ }
1863
+ function getBlueprintActionsDir(agentDir = getAgentDir()) {
1864
+ return join(agentDir, "blueprint-actions");
1865
+ }
1866
+ const EXTENSION_TRANSPILE_CACHE_FORMAT = "ts-source-specifiers";
1867
+ function getExtensionTranspileCacheDir(agentDir = getAgentDir()) {
1868
+ return join(agentDir, "cache", "transpile", `${VERSION}+${EXTENSION_TRANSPILE_CACHE_FORMAT}`);
1869
+ }
1870
+ function getPromptsDir() {
1871
+ return join(getAgentDir(), "prompts");
1872
+ }
1873
+ function getSessionsDir() {
1874
+ return join(getAgentDir(), "sessions");
1875
+ }
1876
+ function getDebugLogPath() {
1877
+ return join(getAgentDir(), `${APP_NAME}-debug.log`);
1878
+ }
1879
+ // dist/core/diagnostic-writer.js
1880
+ const QUEUED = 0;
1881
+ const WRITING = 1;
1882
+ const LANDED = 2;
1883
+ const CLAIMED = 3;
1884
+ const FAILED = 4;
1885
+ const SOURCE = `
1886
+ ${EVAL_WORKER_BUILTIN}
1887
+ const { parentPort } = builtin("node:worker_threads");
1888
+ const { appendFileSync, mkdirSync } = builtin("node:fs");
1889
+ const { dirname } = builtin("node:path");
1890
+ parentPort.on("message", ({ id, path, chunk, state: buffer, createDirectory }) => {
1891
+ const state = new Int32Array(buffer);
1892
+ if (Atomics.compareExchange(state, 0, ${QUEUED}, ${WRITING}) !== ${QUEUED}) {
1893
+ while (Atomics.load(state, 0) === ${CLAIMED}) Atomics.wait(state, 0, ${CLAIMED});
1894
+ return;
1895
+ }
1896
+ let error;
1897
+ try {
1898
+ if (createDirectory) mkdirSync(dirname(path), { recursive: true });
1899
+ appendFileSync(path, chunk);
1900
+ Atomics.store(state, 0, ${LANDED});
1901
+ } catch (cause) {
1902
+ error = String(cause);
1903
+ Atomics.store(state, 0, ${FAILED});
1904
+ }
1905
+ Atomics.notify(state, 0);
1906
+ parentPort.postMessage({ id, error });
1907
+ });
1908
+ `;
1909
+ let worker;
1910
+ let nextId = 0;
1911
+ const outstanding = /* @__PURE__ */ new Map();
1912
+ const counts = /* @__PURE__ */ new Map();
1913
+ function getWorker() {
1914
+ if (worker !== void 0) return worker;
1915
+ const created = new Worker(SOURCE, {
1916
+ eval: true,
1917
+ execArgv: evalWorkerExecArgv()
1918
+ });
1919
+ created.on("message", ({ id, error }) => {
1920
+ outstanding.get(id)?.settle(error === void 0 ? void 0 : new Error(error));
1921
+ });
1922
+ const fail = (error) => {
1923
+ if (worker === created) worker = void 0;
1924
+ for (const append of outstanding.values()) {
1925
+ if (append.worker !== created) continue;
1926
+ Atomics.store(append.state, 0, FAILED);
1927
+ Atomics.notify(append.state, 0);
1928
+ append.settle(error);
1929
+ }
1930
+ };
1931
+ created.on("error", fail);
1932
+ created.on("exit", (code) => fail(/* @__PURE__ */ new Error(`Diagnostic writer exited (${code})`)));
1933
+ created.unref();
1934
+ worker = created;
1935
+ return created;
1936
+ }
1937
+ var DiagnosticWriter = class {
1938
+ pending = /* @__PURE__ */ new Set();
1939
+ onFailure;
1940
+ createDirectory;
1941
+ constructor(onFailure, createDirectory = false) {
1942
+ this.onFailure = onFailure;
1943
+ this.createDirectory = createDirectory;
1944
+ }
1945
+ append(path, chunk) {
1946
+ try {
1947
+ const target = getWorker();
1948
+ const state = new Int32Array(new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT));
1949
+ const id = nextId++;
1950
+ let resolve;
1951
+ const done = new Promise((settle) => {
1952
+ resolve = settle;
1953
+ });
1954
+ const append = {
1955
+ id,
1956
+ path,
1957
+ chunk,
1958
+ state,
1959
+ worker: target,
1960
+ done,
1961
+ settle: (error) => {
1962
+ if (!this.pending.delete(append)) return;
1963
+ outstanding.delete(id);
1964
+ const remaining = (counts.get(target) ?? 1) - 1;
1965
+ if (remaining === 0) {
1966
+ counts.delete(target);
1967
+ target.unref();
1968
+ } else counts.set(target, remaining);
1969
+ if (error !== void 0) this.onFailure(path, error);
1970
+ resolve();
1971
+ }
1972
+ };
1973
+ this.pending.add(append);
1974
+ outstanding.set(id, append);
1975
+ counts.set(target, (counts.get(target) ?? 0) + 1);
1976
+ target.ref();
1977
+ try {
1978
+ target.postMessage({
1979
+ id,
1980
+ path,
1981
+ chunk,
1982
+ state: state.buffer,
1983
+ createDirectory: this.createDirectory
1984
+ });
1985
+ } catch (error) {
1986
+ append.settle(error instanceof Error ? error : new Error(String(error)));
1987
+ }
1988
+ return done;
1989
+ } catch (error) {
1990
+ this.onFailure(path, error instanceof Error ? error : new Error(String(error)));
1991
+ return Promise.resolve();
1992
+ }
1993
+ }
1994
+ async written() {
1995
+ await Promise.all([...this.pending].map((append) => append.done));
1996
+ }
1997
+ flushSync() {
1998
+ for (const append of this.pending) {
1999
+ let error;
2000
+ if (Atomics.compareExchange(append.state, 0, QUEUED, CLAIMED) === QUEUED) {
2001
+ try {
2002
+ if (this.createDirectory) mkdirSync$1(dirname$1(append.path), { recursive: true });
2003
+ appendFileSync(append.path, append.chunk);
2004
+ Atomics.store(append.state, 0, LANDED);
2005
+ } catch (cause) {
2006
+ error = cause instanceof Error ? cause : new Error(String(cause));
2007
+ Atomics.store(append.state, 0, FAILED);
2008
+ }
2009
+ Atomics.notify(append.state, 0);
2010
+ } else while (Atomics.load(append.state, 0) === WRITING) Atomics.wait(append.state, 0, WRITING);
2011
+ if (Atomics.load(append.state, 0) === FAILED) error ??= /* @__PURE__ */ new Error("Diagnostic append failed");
2012
+ append.settle(error);
2013
+ }
2014
+ }
2015
+ };
2016
+ // dist/core/lifecycle-timings.js
2017
+ const STATE_KEY = Symbol.for("@bastani/atomic/lifecycle-timings");
2018
+ const globalWithLifecycleState = globalThis;
2019
+ function getState() {
2020
+ const existing = globalWithLifecycleState[STATE_KEY];
2021
+ if (existing) return existing;
2022
+ const created = {
2023
+ sink: void 0,
2024
+ clock: process.hrtime.bigint,
2025
+ recorded: /* @__PURE__ */ new Set()
2026
+ };
2027
+ globalWithLifecycleState[STATE_KEY] = created;
2028
+ return created;
2029
+ }
2030
+ /** True only when an internal diagnostic adapter has installed a synchronous sink. */
2031
+ function isLifecycleTimingEnabled() {
2032
+ return getState().sink !== void 0;
2033
+ }
2034
+ /**
2035
+ * Install a process-local diagnostic sink.
2036
+ *
2037
+ * The sink must stay synchronous and must not write to the terminal. External
2038
+ * ConPTY and TCP timestamps remain authoritative; these records only attribute
2039
+ * time inside the process. Installing a sink resets the one-shot labels for a
2040
+ * new diagnostic run. The returned function restores the previous adapter.
2041
+ */
2042
+ function installLifecycleTimingSink(sink, clock = process.hrtime.bigint) {
2043
+ const state = getState();
2044
+ const previousSink = state.sink;
2045
+ const previousClock = state.clock;
2046
+ const previousRecorded = new Set(state.recorded);
2047
+ state.sink = sink;
2048
+ state.clock = clock;
2049
+ state.recorded.clear();
2050
+ return () => {
2051
+ state.sink = previousSink;
2052
+ state.clock = previousClock;
2053
+ state.recorded.clear();
2054
+ for (const label of previousRecorded) state.recorded.add(label);
2055
+ };
2056
+ }
2057
+ /** Record the first occurrence of a lifecycle boundary when diagnostics are active. */
2058
+ function markLifecycleTiming(label) {
2059
+ const state = getState();
2060
+ const sink = state.sink;
2061
+ if (!sink || state.recorded.has(label)) return;
2062
+ state.recorded.add(label);
2063
+ try {
2064
+ sink({
2065
+ label,
2066
+ atNs: state.clock(),
2067
+ pid: process.pid
2068
+ });
2069
+ } catch {}
2070
+ }
2071
+ /** Variables naming the startup trace file; `PI_` is the legacy alias, as for every Atomic variable. */
2072
+ const STARTUP_TRACE_ENV_NAMES = ["ATOMIC_STARTUP_TRACE", "PI_STARTUP_TRACE"];
2073
+ let traceWriter;
2074
+ /**
2075
+ * Write the trace lines still waiting for the writer's thread, once a quit has begun. Windows ends an isolated engine
2076
+ * as soon as its host has the quit acknowledgement, without running exit handlers, so a line still waiting then would
2077
+ * be lost. Does nothing when no trace is installed.
2078
+ */
2079
+ function flushLifecycleTraceAtQuit() {
2080
+ getState().flushTrace?.();
2081
+ }
2082
+ /**
2083
+ * When `ATOMIC_STARTUP_TRACE` names a file, append this process's start and each lifecycle mark to it, one JSON line
2084
+ * each. A host and the engine child it starts inherit the variable, so one file holds both timelines. Lines are
2085
+ * appended off the event loop in mark order; whatever has not reached the file when the process exits is written then.
2086
+ * Does nothing when the variable is unset or another diagnostic sink is already installed. Returns the function that
2087
+ * uninstalls it.
2088
+ */
2089
+ function installLifecycleTraceFromEnv(env = process.env) {
2090
+ const file = STARTUP_TRACE_ENV_NAMES.map((name) => env[name]).find((value) => value !== void 0 && value !== "");
2091
+ if (!file || getState().sink) return void 0;
2092
+ const writer = new DiagnosticWriter(() => {});
2093
+ traceWriter = writer;
2094
+ const write = (label, epochMs) => {
2095
+ const line = {
2096
+ label,
2097
+ epochMs,
2098
+ pid: process.pid,
2099
+ ppid: process.ppid
2100
+ };
2101
+ writer.append(file, `${JSON.stringify(line)}\n`);
2102
+ };
2103
+ const writeRemainingAtExit = () => writer.flushSync();
2104
+ process.once("exit", writeRemainingAtExit);
2105
+ const state = getState();
2106
+ state.flushTrace = writeRemainingAtExit;
2107
+ write("process-start", performance.timeOrigin);
2108
+ const uninstallSink = installLifecycleTimingSink((record) => write(record.label, performance.timeOrigin + performance.now()));
2109
+ return () => {
2110
+ uninstallSink();
2111
+ process.removeListener("exit", writeRemainingAtExit);
2112
+ if (traceWriter === writer) traceWriter = void 0;
2113
+ if (state.flushTrace === writeRemainingAtExit) state.flushTrace = void 0;
2114
+ };
2115
+ }
2116
+ // dist/modes/interactive-engine/engine-heap.js
2117
+ const MIB = 1048576;
2118
+ const ENGINE_HEAP_SHARE_OF_SYSTEM_MEMORY = .5;
2119
+ /**
2120
+ * Options that set the size of V8's heap. Node applies a percentage of memory over an old space size, and V8 an old
2121
+ * space size over a total heap size, which then still sizes the young generation.
2122
+ */
2123
+ const HEAP_SIZE_OPTIONS = /* @__PURE__ */ new Set([
2124
+ "--max-old-space-size",
2125
+ "--max-old-space-size-percentage",
2126
+ "--max-heap-size"
2127
+ ]);
2128
+ /** The young generation's size, which adds to whichever heap size applies. */
2129
+ const YOUNG_GENERATION_SIZE_OPTION = "--max-semi-space-size";
2130
+ /** The heap options that are V8's own: V8 also reads them with one leading dash, which Node passes on to it. */
2131
+ const V8_HEAP_OPTIONS = /* @__PURE__ */ new Set([
2132
+ "--max-old-space-size",
2133
+ "--max-heap-size",
2134
+ YOUNG_GENERATION_SIZE_OPTION
2135
+ ]);
2136
+ /** The heap flags on a command line (`process.execArgv`). Node and V8 match `_` as `-` in an option's name. */
2137
+ function commandLineHeapFlags(execArgv) {
2138
+ const last = /* @__PURE__ */ new Map();
2139
+ for (let index = 0; index < execArgv.length; index++) {
2140
+ const flag = execArgv[index];
2141
+ if (flag === "--") break;
2142
+ if (!flag.startsWith("-")) continue;
2143
+ const dashes = flag.startsWith("--") ? 2 : 1;
2144
+ const equals = flag.indexOf("=");
2145
+ const name = `--${(equals === -1 ? flag : flag.slice(0, equals)).slice(dashes).replaceAll("_", "-")}`;
2146
+ if (!HEAP_SIZE_OPTIONS.has(name) && name !== YOUNG_GENERATION_SIZE_OPTION) continue;
2147
+ if (dashes === 1 && !V8_HEAP_OPTIONS.has(name)) continue;
2148
+ const value = execArgv[index + 1];
2149
+ const valueFollows = equals === -1 && value !== void 0 && !value.startsWith("-");
2150
+ last.delete(name);
2151
+ last.set(name, valueFollows ? [flag, value] : [flag]);
2152
+ if (valueFollows) index++;
2153
+ }
2154
+ return {
2155
+ setsHeapSize: [...last.keys()].some((name) => HEAP_SIZE_OPTIONS.has(name)),
2156
+ flags: [...last.values()].flat()
2157
+ };
2158
+ }
2159
+ /** Whether a command line (`process.execArgv`) sets a heap size, which a process started with it keeps. */
2160
+ function commandLineSetsHeapSize(execArgv) {
2161
+ return commandLineHeapFlags(execArgv).setsHeapSize;
2162
+ }
2163
+ /**
2164
+ * Node flags that size the interactive engine's V8 heap. The engine hosts every in-process subagent, so V8's default limit (about 4 GiB) caps the whole fleet regardless of machine size. Under Node the engine
2165
+ * gets half of system memory, or of its container's memory limit when that is smaller, when this exceeds the
2166
+ * current limit. A heap size given to Node (`--max-old-space-size`, `--max-old-space-size-percentage` or
2167
+ * `--max-heap-size`) in `NODE_OPTIONS`, which the engine inherits, or on the host's own command line wins: the engine
2168
+ * gets the host's command-line heap flags, the last one for each option, so that Node sizes its heap as it sized the
2169
+ * host's. `ATOMIC_HEAP_MB` sets the size in MiB or, as `0`, turns automatic sizing off. A young generation size
2170
+ * (`--max-semi-space-size`) on the host's command line goes to the engine in every case. Other runtimes do not use V8
2171
+ * and get no flags.
2172
+ */
2173
+ function engineHeapRuntimeArgs(inputs) {
2174
+ if (!inputs.runsOnNode) return [];
2175
+ const host = commandLineHeapFlags(inputs.execArgv);
2176
+ if (host.setsHeapSize) return [...host.flags];
2177
+ const youngGeneration = [...host.flags];
2178
+ if (nodeOptionsFromEnvironment(inputs.nodeOptions).some((option) => HEAP_SIZE_OPTIONS.has(option.name))) return youngGeneration;
2179
+ const configured = inputs.configuredHeapMb?.trim();
2180
+ if (configured) {
2181
+ const heapMb = Number(configured);
2182
+ if (Number.isSafeInteger(heapMb) && heapMb >= 0) return heapMb === 0 ? youngGeneration : [...youngGeneration, `--max-old-space-size=${heapMb}`];
2183
+ }
2184
+ const constrained = inputs.constrainedMemoryBytes;
2185
+ const memoryBytes = constrained !== void 0 && constrained > 0 ? Math.min(inputs.totalMemoryBytes, constrained) : inputs.totalMemoryBytes;
2186
+ const targetMb = Math.floor(memoryBytes * ENGINE_HEAP_SHARE_OF_SYSTEM_MEMORY / MIB);
2187
+ return targetMb > Math.floor(inputs.currentHeapLimitBytes / MIB) ? [...youngGeneration, `--max-old-space-size=${targetMb}`] : youngGeneration;
2188
+ }
2189
+ function engineHeapRuntimeArgsForHost(runsOnNode) {
2190
+ if (!runsOnNode) return [];
2191
+ return engineHeapRuntimeArgs({
2192
+ runsOnNode,
2193
+ totalMemoryBytes: totalmem(),
2194
+ constrainedMemoryBytes: process.constrainedMemory(),
2195
+ currentHeapLimitBytes: getHeapStatistics().heap_size_limit,
2196
+ nodeOptions: process.env.NODE_OPTIONS,
2197
+ execArgv: process.execArgv,
2198
+ configuredHeapMb: getEnvValue(ENV_HEAP_MB)
2199
+ });
2200
+ }
2201
+ // dist/utils/compile-cache.js
2202
+ var compile_cache_exports = /* @__PURE__ */ __exportAll({
2203
+ COMPILE_CACHE_ENGINE_MATCH_HOST_ENV: () => COMPILE_CACHE_ENGINE_MATCH_HOST_ENV,
2204
+ COMPILE_CACHE_ENGINE_WARMUP_ENV: () => COMPILE_CACHE_ENGINE_WARMUP_ENV,
2205
+ compileCacheBaseDir: () => compileCacheBaseDir,
2206
+ compileCacheBuildId: () => compileCacheBuildId,
2207
+ compileCacheDeferral: () => compileCacheDeferral,
2208
+ compileCacheHelperRuntime: () => compileCacheHelperRuntime,
2209
+ compileCacheStartMode: () => compileCacheStartMode,
2210
+ compileCacheWarmMarker: () => compileCacheWarmMarker,
2211
+ currentCompileCacheWarmMarker: () => currentCompileCacheWarmMarker,
2212
+ enablePersistentCompileCache: () => enablePersistentCompileCache,
2213
+ engineCompileCacheResetHeapMb: () => engineCompileCacheResetHeapMb,
2214
+ flushPersistentCompileCache: () => flushPersistentCompileCache,
2215
+ hostAutoSizedEngineHeap: () => hostAutoSizedEngineHeap,
2216
+ isCiValue: () => isCiValue,
2217
+ startsCompileCacheHelper: () => startsCompileCacheHelper
2218
+ });
2219
+ const __atomicDistModuleUrl$2 = new URL("../utils/compile-cache.js", import.meta.url).href;
2220
+ const compileCacheApi = nodeModule;
2221
+ const COMPILE_CACHE_ENGINE_WARMUP_ENV = "ATOMIC_INTERNAL_COMPILE_CACHE_WARMUP";
2222
+ const COMPILE_CACHE_ENGINE_MATCH_HOST_ENV = "ATOMIC_INTERNAL_COMPILE_CACHE_MATCH_HOST";
2223
+ const ENGINE_WORKER_HEAP_MB_SYMBOL = /* @__PURE__ */ Symbol.for("atomic.engine-worker-heap-mb.v1");
2224
+ function compileCacheStartMode(input) {
2225
+ if (input.platform !== "win32" || input.runtimeIsBun || input.unsupported) return "enable";
2226
+ if (input.alreadyEnabled || input.disabled || !input.interactive || !input.helperRuntime) return "enable";
2227
+ return input.warm() ? "enable" : "defer";
2228
+ }
2229
+ function startsCompileCacheHelper(env) {
2230
+ return !isCiValue(env.CI);
2231
+ }
2232
+ function isCiValue(value) {
2233
+ if (value === void 0) return false;
2234
+ const normalized = value.trim().toLowerCase();
2235
+ return normalized !== "" && normalized !== "0" && normalized !== "false";
2236
+ }
2237
+ const HEAP_SIZE_FLAG = /^--max[-_]old[-_]space[-_]size=\d+$/;
2238
+ const HEAP_SIZE_OPTION_NAMES = /* @__PURE__ */ new Set([
2239
+ "--max-old-space-size",
2240
+ "--max-old-space-size-percentage",
2241
+ "--max-heap-size"
2242
+ ]);
2243
+ const V8_HEAP_SIZE_OPTION_NAMES = /* @__PURE__ */ new Set(["--max-old-space-size", "--max-heap-size"]);
2244
+ const PRELOAD_FLAGS = /* @__PURE__ */ new Set([
2245
+ "-r",
2246
+ "--require",
2247
+ "--import",
2248
+ "--loader",
2249
+ "--experimental-loader"
2250
+ ]);
2251
+ function flagsSetHeapSize(flags) {
2252
+ for (const flag of flags) {
2253
+ if (flag === "--") break;
2254
+ if (!flag.startsWith("-")) continue;
2255
+ const dashes = flag.startsWith("--") ? 2 : 1;
2256
+ const equals = flag.indexOf("=");
2257
+ const name = `--${(equals === -1 ? flag : flag.slice(0, equals)).slice(dashes).replaceAll("_", "-")}`;
2258
+ if (!HEAP_SIZE_OPTION_NAMES.has(name)) continue;
2259
+ if (dashes === 1 && !V8_HEAP_SIZE_OPTION_NAMES.has(name)) continue;
2260
+ return true;
2261
+ }
2262
+ return false;
2263
+ }
2264
+ function parseAutoHeapMb(flag) {
2265
+ if (!HEAP_SIZE_FLAG.test(flag)) return void 0;
2266
+ const mb = Number(flag.slice(flag.indexOf("=") + 1));
2267
+ return Number.isSafeInteger(mb) && mb > 0 ? mb : void 0;
2268
+ }
2269
+ function hostAutoSizedEngineHeap(hostExecArgv, nodeOptions, engineRuntimeArgs) {
2270
+ if (flagsSetHeapSize(hostExecArgv)) return false;
2271
+ const words = splitNodeOptions(nodeOptions ?? "");
2272
+ if (!words || flagsSetHeapSize(words)) return false;
2273
+ return engineRuntimeArgs.filter((flag) => parseAutoHeapMb(flag) !== void 0 && !hostExecArgv.includes(flag)).length === 1;
2274
+ }
2275
+ function engineCompileCacheResetHeapMb(input) {
2276
+ if (input.runtimeIsBun || input.unsupported || input.alreadyEnabled || input.disabled || !input.matchHostTag) return;
2277
+ const words = splitNodeOptions(input.nodeOptions ?? "");
2278
+ if (!words || flagsSetHeapSize(words)) return void 0;
2279
+ const heapValues = input.execArgv.map(parseAutoHeapMb).filter((mb) => mb !== void 0);
2280
+ return heapValues.length === 1 ? heapValues[0] : void 0;
2281
+ }
2282
+ function keptFlags(flags) {
2283
+ const kept = [];
2284
+ for (let index = 0; index < flags.length; index++) {
2285
+ const flag = flags[index];
2286
+ if (HEAP_SIZE_FLAG.test(flag)) {
2287
+ kept.push(flag);
2288
+ continue;
2289
+ }
2290
+ const name = flag.includes("=") ? flag.slice(0, flag.indexOf("=")) : flag;
2291
+ if (!PRELOAD_FLAGS.has(name)) return void 0;
2292
+ if (!flag.includes("=")) index++;
2293
+ }
2294
+ return kept;
2295
+ }
2296
+ function compileCacheHelperRuntime(execArgv, env) {
2297
+ if (env.NODE_V8_COVERAGE !== void 0) return void 0;
2298
+ const words = splitNodeOptions(env.NODE_OPTIONS ?? "");
2299
+ if (!words) return void 0;
2300
+ const command = keptFlags(execArgv);
2301
+ const options = keptFlags(words);
2302
+ if (!command || !options) return void 0;
2303
+ return {
2304
+ execArgv: command,
2305
+ nodeOptions: options.join(" ")
2306
+ };
2307
+ }
2308
+ function compileCacheBuildId(build) {
2309
+ let hash = 2166136261;
2310
+ for (let index = 0; index < build.length; index++) {
2311
+ hash ^= build.charCodeAt(index);
2312
+ hash = Math.imul(hash, 16777619) >>> 0;
2313
+ }
2314
+ return hash.toString(16).padStart(8, "0");
2315
+ }
2316
+ function compileCacheBaseDir() {
2317
+ return join$1(tmpdir(), "node-compile-cache");
2318
+ }
2319
+ function compileCacheWarmMarker(options) {
2320
+ const tag = `${options.nodeVersion}-${options.arch}-${(options.versionTag >>> 0).toString(16).padStart(8, "0")}${options.uid === void 0 ? "" : `-${options.uid}`}`;
2321
+ return join$1(options.baseDir, tag, `atomic-warm-${options.buildId}`);
2322
+ }
2323
+ function currentCompileCacheWarmMarker(buildId) {
2324
+ return compileCacheWarmMarker({
2325
+ baseDir: compileCacheBaseDir(),
2326
+ nodeVersion: process.version,
2327
+ arch: process.arch,
2328
+ versionTag: cachedDataVersionTag(),
2329
+ uid: typeof process.getuid === "function" ? process.getuid() : void 0,
2330
+ buildId
2331
+ });
2332
+ }
2333
+ let deferral;
2334
+ function enablePersistentCompileCache(options = {}) {
2335
+ try {
2336
+ const runtimeIsBun = "bun" in process.versions;
2337
+ const unsupported = typeof compileCacheApi.enableCompileCache !== "function";
2338
+ const alreadyEnabled = compileCacheApi.getCompileCacheDir?.() !== void 0;
2339
+ const disabled = process.env.NODE_DISABLE_COMPILE_CACHE !== void 0;
2340
+ const resetHeapMb = engineCompileCacheResetHeapMb({
2341
+ runtimeIsBun,
2342
+ unsupported,
2343
+ alreadyEnabled,
2344
+ disabled,
2345
+ matchHostTag: options.matchHostTag === true,
2346
+ execArgv: process.execArgv,
2347
+ nodeOptions: process.env.NODE_OPTIONS
2348
+ });
2349
+ if (resetHeapMb !== void 0) try {
2350
+ const beforeTag = cachedDataVersionTag();
2351
+ setFlagsFromString("--max-old-space-size=0");
2352
+ if (cachedDataVersionTag() === beforeTag) setFlagsFromString(`--max-old-space-size=${resetHeapMb}`);
2353
+ else globalThis[ENGINE_WORKER_HEAP_MB_SYMBOL] = resetHeapMb;
2354
+ } catch {}
2355
+ const runtime = compileCacheHelperRuntime(process.execArgv, process.env);
2356
+ const buildId = compileCacheBuildId(`${__atomicDistModuleUrl$2}\0${options.build ?? ""}`);
2357
+ if (compileCacheStartMode({
2358
+ platform: process.platform,
2359
+ runtimeIsBun,
2360
+ unsupported,
2361
+ alreadyEnabled,
2362
+ disabled,
2363
+ interactive: options.interactive === true && options.build !== void 0,
2364
+ helperRuntime: runtime !== void 0,
2365
+ warm: () => existsSync$1(currentCompileCacheWarmMarker(buildId))
2366
+ }) === "defer" && runtime) {
2367
+ deferral = {
2368
+ buildId,
2369
+ runtime,
2370
+ helper: startsCompileCacheHelper(process.env)
2371
+ };
2372
+ return;
2373
+ }
2374
+ compileCacheApi.enableCompileCache?.();
2375
+ } catch {}
2376
+ }
2377
+ function compileCacheDeferral() {
2378
+ return deferral;
2379
+ }
2380
+ function flushPersistentCompileCache() {
2381
+ try {
2382
+ compileCacheApi.flushCompileCache?.();
2383
+ } catch {}
2384
+ }
2385
+ // dist/utils/compile-cache-deferral.js
2386
+ /**
2387
+ * This process's compile-cache deferral (see `compile-cache.ts`), for the modules that load after the process's entry.
2388
+ *
2389
+ * `compile-cache.ts` loads with the entry (`cli.ts`), so a process that started before an update replaced the
2390
+ * installation keeps the copy it started with while it loads later modules from the update. 0.10.3's copy has neither
2391
+ * a deferral nor the engine warmup variable, and a named import of either would fail to link there; read through here,
2392
+ * such a process is one that never deferred its cache, which it is.
2393
+ */
2394
+ const deferrals = compile_cache_exports;
2395
+ /** The cache this process left cold for a helper, if any. */
2396
+ function processCompileCacheDeferral() {
2397
+ return deferrals.compileCacheDeferral?.();
2398
+ }
2399
+ /** The environment an engine child gets when this process leaves its cold cache to a helper that warms the engine's too. */
2400
+ function engineCompileCacheWarmupEnv() {
2401
+ const name = deferrals.COMPILE_CACHE_ENGINE_WARMUP_ENV;
2402
+ return name !== void 0 && processCompileCacheDeferral() ? { [name]: "1" } : {};
2403
+ }
2404
+ /**
2405
+ * The environment an auto-sized Node engine child gets so on Node 22 it aligns its compile-cache tag with the
2406
+ * untouched host (#6222). Omitted on Bun or when the host itself passed an explicit heap size.
2407
+ */
2408
+ function engineCompileCacheMatchHostEnv(engineRuntimeArgs) {
2409
+ if ("bun" in process.versions) return {};
2410
+ const name = deferrals.COMPILE_CACHE_ENGINE_MATCH_HOST_ENV;
2411
+ const check = deferrals.hostAutoSizedEngineHeap;
2412
+ if (name === void 0 || check === void 0) return {};
2413
+ return check(process.execArgv, process.env.NODE_OPTIONS, engineRuntimeArgs) ? { [name]: "1" } : {};
2414
+ }
2415
+ // dist/utils/windows-cwd.js
2416
+ /** Safe Win32 path length threshold for `CreateProcessW` `lpCurrentDirectory` without an extended `\\?\` prefix. */
2417
+ const SAFE_WINDOWS_CWD_LENGTH = 248;
2418
+ /** Maximum share of the timeout budget spent resolving protected directories' realpaths before probing local candidates. */
2419
+ const MAX_PROTECTED_REALPATH_BUDGET_MS = 50;
2420
+ function isAsciiLetter(code) {
2421
+ return code >= 65 && code <= 90 || code >= 97 && code <= 122;
2422
+ }
2423
+ function isDriveRootPrefix(slashed) {
2424
+ return slashed.length >= 3 && isAsciiLetter(slashed.charCodeAt(0)) && slashed[1] === ":" && slashed[2] === "\\";
2425
+ }
2426
+ function normalizeUncPath(slashed) {
2427
+ const rest = slashed.slice(2);
2428
+ const firstSep = rest.indexOf("\\");
2429
+ if (firstSep <= 0) return void 0;
2430
+ const server = rest.slice(0, firstSep);
2431
+ if (server === "." || server === "..") return void 0;
2432
+ const afterServer = rest.slice(firstSep + 1);
2433
+ const secondSep = afterServer.indexOf("\\");
2434
+ const share = secondSep === -1 ? afterServer : afterServer.slice(0, secondSep);
2435
+ if (share === "" || share === "." || share === "..") return void 0;
2436
+ return win32$1.resolve(slashed);
2437
+ }
2438
+ /**
2439
+ * Normalizes a fully-qualified Windows directory path for containment comparison.
2440
+ *
2441
+ * Strips extended-length and Win32 device prefixes (`\\?\`, `\\.\`, `\\?\UNC\`) so aliased paths compare
2442
+ * equal to their standard counterparts, preserves trailing separators on drive and share roots, and
2443
+ * rejects relative paths, bare drives (`C:`), drive-relative paths (`C:foo`), rooted-without-drive paths
2444
+ * (`\Windows`), raw volume devices (`\\?\C:`, `\\?\Volume{...}` without `\`), incomplete UNC roots, and
2445
+ * NUL bytes.
2446
+ */
2447
+ function normalizeWindowsPathForCompare(value) {
2448
+ if (value === "" || value.includes("\0")) return void 0;
2449
+ const slashed = value.replaceAll("/", "\\");
2450
+ if (slashed.startsWith("\\\\?\\") || slashed.startsWith("\\\\.\\")) {
2451
+ const rest = slashed.slice(4);
2452
+ if (rest.length >= 4 && rest.slice(0, 4).toLowerCase() === "unc\\") return normalizeUncPath(`\\\\${rest.slice(4)}`);
2453
+ if (isDriveRootPrefix(rest)) return win32$1.resolve(rest);
2454
+ if (rest.length > 9 && rest.slice(0, 7).toLowerCase() === "volume{") {
2455
+ const sepIndex = rest.indexOf("\\");
2456
+ if (sepIndex <= 8 || rest[sepIndex - 1] !== "}") return void 0;
2457
+ const root = `\\\\?\\${rest.slice(0, sepIndex + 1)}`;
2458
+ const tail = rest.slice(sepIndex + 1);
2459
+ return `${root}${tail === "" ? "" : win32$1.resolve("C:\\", tail).slice(3)}`;
2460
+ }
2461
+ return;
2462
+ }
2463
+ if (slashed.startsWith("\\\\")) return normalizeUncPath(slashed);
2464
+ if (isDriveRootPrefix(slashed)) return win32$1.resolve(slashed);
2465
+ }
2466
+ /**
2467
+ * Formats a normalized comparison path for Win32 filesystem / `CreateProcessW` APIs:
2468
+ * keeps short paths (< 248 chars) plain and ensures paths >= 248 chars carry the proper
2469
+ * extended-length prefix (`\\?\` for drive paths, `\\?\UNC\server\share\...` for UNC paths).
2470
+ */
2471
+ function toSpawnWindowsPath(comparePath) {
2472
+ if (comparePath.startsWith("\\\\?\\") || comparePath.length < SAFE_WINDOWS_CWD_LENGTH) return comparePath;
2473
+ if (comparePath.startsWith("\\\\")) return `\\\\?\\UNC\\${comparePath.slice(2)}`;
2474
+ return `\\\\?\\${comparePath}`;
2475
+ }
2476
+ function isAbsoluteWindowsPath(value) {
2477
+ return normalizeWindowsPathForCompare(value) !== void 0;
2478
+ }
2479
+ /** Returns the normalized drive, UNC share, or volume root (always ending with `\`) for an absolute Windows path. */
2480
+ function windowsDriveRoot(value) {
2481
+ if (value === void 0) return void 0;
2482
+ const normalized = normalizeWindowsPathForCompare(value);
2483
+ if (normalized === void 0) return void 0;
2484
+ if (normalized.startsWith("\\\\?\\")) {
2485
+ const sepIndex = normalized.indexOf("\\", 4);
2486
+ return sepIndex === -1 ? void 0 : normalized.slice(0, sepIndex + 1);
2487
+ }
2488
+ const root = win32$1.parse(normalized).root;
2489
+ if (root.length <= 1) return void 0;
2490
+ return root.endsWith("\\") ? root : `${root}\\`;
2491
+ }
2492
+ function isDriveRootWindowsPath(normalized) {
2493
+ const root = windowsDriveRoot(normalized);
2494
+ return root !== void 0 && normalized.toLowerCase() === root.toLowerCase();
2495
+ }
2496
+ function addNonRootWindowsDir(target, seen, candidate) {
2497
+ const normalized = normalizeWindowsPathForCompare(candidate);
2498
+ if (normalized === void 0 || isDriveRootWindowsPath(normalized)) return;
2499
+ const key = normalized.toLowerCase();
2500
+ if (seen.has(key)) return;
2501
+ seen.add(key);
2502
+ target.push(normalized);
2503
+ }
2504
+ /**
2505
+ * Returns the install-root directories enclosing `entryDir` that background helpers must not keep as their working
2506
+ * directory on Windows (npm/pnpm/bun package root + `@scope`/`node_modules`, standalone binary `versions/<ver>` +
2507
+ * install root, or `dist/utils` package root). Never promotes a drive or share root to an inferred protected ancestor.
2508
+ */
2509
+ function collectInstallProtectedDirs(entryDir) {
2510
+ if (entryDir === void 0 || entryDir === "") return [];
2511
+ const normalized = normalizeWindowsPathForCompare(entryDir);
2512
+ if (normalized === void 0) return [];
2513
+ const result = [normalized];
2514
+ const seen = /* @__PURE__ */ new Set([normalized.toLowerCase()]);
2515
+ const add = (dir) => addNonRootWindowsDir(result, seen, dir);
2516
+ const parent = win32$1.dirname(normalized);
2517
+ const parentName = win32$1.basename(parent).toLowerCase();
2518
+ const ownName = win32$1.basename(normalized).toLowerCase();
2519
+ const grandParent = win32$1.dirname(parent);
2520
+ const grandParentName = win32$1.basename(grandParent).toLowerCase();
2521
+ let packageDir = normalized;
2522
+ if (parentName === "builtin" && grandParentName === "dist") {
2523
+ packageDir = win32$1.dirname(grandParent);
2524
+ add(grandParent);
2525
+ add(packageDir);
2526
+ } else if (parentName === "builtin") {
2527
+ const versionDir = grandParent;
2528
+ packageDir = versionDir;
2529
+ add(versionDir);
2530
+ const versionDirName = win32$1.basename(versionDir).toLowerCase();
2531
+ const versionsParent = win32$1.dirname(versionDir);
2532
+ if (win32$1.basename(versionsParent).toLowerCase() === "versions") {
2533
+ add(versionsParent);
2534
+ add(win32$1.dirname(versionsParent));
2535
+ } else if (versionDirName === "current" || versionDirName === "atomic-current") add(versionsParent);
2536
+ } else if (ownName === "utils" && parentName === "dist") {
2537
+ packageDir = grandParent;
2538
+ add(parent);
2539
+ add(packageDir);
2540
+ } else if (parentName === "versions") {
2541
+ add(parent);
2542
+ add(grandParent);
2543
+ } else if (ownName === "current" || ownName === "atomic-current") add(parent);
2544
+ const pkgParent = win32$1.dirname(packageDir);
2545
+ const pkgParentName = win32$1.basename(pkgParent).toLowerCase();
2546
+ const pkgGrandParent = win32$1.dirname(pkgParent);
2547
+ const pkgGrandParentName = win32$1.basename(pkgGrandParent).toLowerCase();
2548
+ if (pkgParentName.startsWith("@") && pkgGrandParentName === "node_modules") {
2549
+ add(pkgParent);
2550
+ add(pkgGrandParent);
2551
+ } else if (pkgParentName === "node_modules") add(pkgParent);
2552
+ return result;
2553
+ }
2554
+ function isSubpathOrSame(folderNormalized, candidateNormalized) {
2555
+ const rel = win32$1.relative(folderNormalized.toLowerCase(), candidateNormalized.toLowerCase());
2556
+ return rel !== ".." && !rel.startsWith("..\\") && !win32$1.isAbsolute(rel);
2557
+ }
2558
+ function conflictsWithNormalizedFolder(folderNormalized, candidateNormalized) {
2559
+ if (isDriveRootWindowsPath(folderNormalized)) return folderNormalized.toLowerCase() === candidateNormalized.toLowerCase();
2560
+ return isSubpathOrSame(folderNormalized, candidateNormalized);
2561
+ }
2562
+ function isInsideProtectedFolder(folder, candidate) {
2563
+ if (candidate.unverifiedLink) return true;
2564
+ if (folder.real !== void 0 && candidate.real !== void 0) {
2565
+ if (isDriveRootWindowsPath(folder.real)) return folder.real.toLowerCase() === candidate.real.toLowerCase();
2566
+ if (isSubpathOrSame(folder.real, candidate.real)) return true;
2567
+ if (!isDriveRootWindowsPath(folder.lexical) && isSubpathOrSame(folder.lexical, candidate.lexical)) return true;
2568
+ return false;
2569
+ }
2570
+ if (conflictsWithNormalizedFolder(folder.lexical, candidate.lexical)) return true;
2571
+ if (folder.real !== void 0 && conflictsWithNormalizedFolder(folder.real, candidate.lexical)) return true;
2572
+ if (candidate.real !== void 0 && conflictsWithNormalizedFolder(folder.lexical, candidate.real)) return true;
2573
+ return false;
2574
+ }
2575
+ function preferredCandidatePath(candidate) {
2576
+ return toSpawnWindowsPath(candidate.real ?? candidate.lexical);
2577
+ }
2578
+ /**
2579
+ * Win32 `CreateProcessW` rejects `lpCurrentDirectory` >= `MAX_PATH` (even with `\\?\`) when Windows' default
2580
+ * `LongPathsEnabled = 0` is in effect. Prefer a short (< 248-char) verified directory outside the project whenever
2581
+ * one is available so kill commands work across both default Windows installs and `LongPathsEnabled = 1` hosts.
2582
+ */
2583
+ function isShortWindowsSpawnPath(spawnPath) {
2584
+ return !spawnPath.startsWith("\\\\?\\") && spawnPath.length < SAFE_WINDOWS_CWD_LENGTH;
2585
+ }
2586
+ function probePathFor(rawDir, lexical) {
2587
+ if (rawDir.length >= SAFE_WINDOWS_CWD_LENGTH && !rawDir.startsWith("\\\\?\\")) return toSpawnWindowsPath(lexical);
2588
+ return rawDir;
2589
+ }
2590
+ function readProcessCwd() {
2591
+ try {
2592
+ return process.cwd();
2593
+ } catch {
2594
+ return;
2595
+ }
2596
+ }
2597
+ function collectRawProtectedDirs(extra) {
2598
+ const result = [];
2599
+ const seen = /* @__PURE__ */ new Set();
2600
+ const add = (dir) => {
2601
+ if (dir === void 0) return;
2602
+ const normalized = normalizeWindowsPathForCompare(dir);
2603
+ if (normalized === void 0) return;
2604
+ const key = normalized.toLowerCase();
2605
+ if (seen.has(key)) return;
2606
+ seen.add(key);
2607
+ result.push(dir);
2608
+ };
2609
+ add(readProcessCwd());
2610
+ for (const dir of extra ?? []) add(dir);
2611
+ return result;
2612
+ }
2613
+ function dedupeCandidates(rawList) {
2614
+ const deduped = [];
2615
+ const seen = /* @__PURE__ */ new Set();
2616
+ for (const item of rawList) {
2617
+ if (item === void 0 || item === "") continue;
2618
+ const key = item.toLowerCase();
2619
+ if (seen.has(key)) continue;
2620
+ seen.add(key);
2621
+ deduped.push(item);
2622
+ }
2623
+ return deduped;
2624
+ }
2625
+ function buildCandidates(protectedDirs, commandPath, preferCommandDir) {
2626
+ const tempDir = tmpdir();
2627
+ const normalizedCommand = commandPath === void 0 ? void 0 : normalizeWindowsPathForCompare(commandPath);
2628
+ const commandDir = normalizedCommand === void 0 ? void 0 : win32$1.dirname(normalizedCommand);
2629
+ const commandRoot = windowsDriveRoot(normalizedCommand);
2630
+ const tempRoot = windowsDriveRoot(tempDir);
2631
+ const protectedRoots = [];
2632
+ for (const folder of protectedDirs) {
2633
+ protectedRoots.push(windowsDriveRoot(folder.real));
2634
+ protectedRoots.push(windowsDriveRoot(folder.lexical));
2635
+ }
2636
+ const middle = preferCommandDir ? [commandDir, tempDir] : [tempDir, commandDir];
2637
+ return dedupeCandidates([
2638
+ process.env.SystemRoot,
2639
+ process.env.windir,
2640
+ "C:\\Windows",
2641
+ ...middle,
2642
+ commandRoot,
2643
+ tempRoot,
2644
+ ...protectedRoots,
2645
+ windowsDriveRoot(process.env.SystemRoot),
2646
+ windowsDriveRoot(process.env.windir),
2647
+ "C:\\"
2648
+ ]);
2649
+ }
2650
+ function boundedFsCall(work, budgetMs, signal) {
2651
+ if (signal?.aborted || budgetMs <= 0) {
2652
+ work.catch(() => {});
2653
+ return Promise.resolve(void 0);
2654
+ }
2655
+ return new Promise((resolve) => {
2656
+ let settled = false;
2657
+ const done = (value) => {
2658
+ if (settled) return;
2659
+ settled = true;
2660
+ clearTimeout(timer);
2661
+ signal?.removeEventListener("abort", onAbort);
2662
+ resolve(value);
2663
+ };
2664
+ const onAbort = () => done(void 0);
2665
+ const timer = setTimeout(() => done(void 0), budgetMs);
2666
+ timer.unref?.();
2667
+ signal?.addEventListener("abort", onAbort, { once: true });
2668
+ work.then((value) => done(value), () => done(void 0));
2669
+ });
2670
+ }
2671
+ async function tryRealPathAsync(dir, deadline, signal) {
2672
+ const resolved = await boundedFsCall(realpath(dir), deadline - Date.now(), signal);
2673
+ return resolved === void 0 ? void 0 : normalizeWindowsPathForCompare(resolved);
2674
+ }
2675
+ async function resolveProtectedDirAsync(rawDir, deadline, signal) {
2676
+ const lexical = normalizeWindowsPathForCompare(rawDir);
2677
+ if (lexical === void 0) return void 0;
2678
+ return {
2679
+ lexical,
2680
+ real: await tryRealPathAsync(probePathFor(rawDir, lexical), deadline, signal)
2681
+ };
2682
+ }
2683
+ async function resolveCandidateDirAsync(rawDir, deadline, signal) {
2684
+ if (signal?.aborted || deadline - Date.now() <= 0) return void 0;
2685
+ const lexical = normalizeWindowsPathForCompare(rawDir);
2686
+ if (lexical === void 0) return void 0;
2687
+ const probe = probePathFor(rawDir, lexical);
2688
+ if (!(await boundedFsCall(stat(probe), deadline - Date.now(), signal))?.isDirectory()) return void 0;
2689
+ const real = await tryRealPathAsync(probe, deadline, signal);
2690
+ let unverifiedLink = false;
2691
+ if (real === void 0 && !signal?.aborted && deadline - Date.now() > 0) unverifiedLink = (await boundedFsCall(lstat(probe), deadline - Date.now(), signal))?.isSymbolicLink() === true;
2692
+ return {
2693
+ lexical,
2694
+ real,
2695
+ unverifiedLink
2696
+ };
2697
+ }
2698
+ /**
2699
+ * Asynchronously selects a safe existing Windows working directory outside `process.cwd()` (and any extra
2700
+ * protected folders) within a bounded time budget without blocking the event loop.
2701
+ */
2702
+ async function resolveSafeWindowsWorkingDirectoryAsync(options = {}) {
2703
+ const { signal } = options;
2704
+ if (signal?.aborted) return void 0;
2705
+ const totalMs = Math.max(0, options.timeoutMs ?? 100);
2706
+ const startedAt = Date.now();
2707
+ const overallDeadline = startedAt + totalMs;
2708
+ const protectedDeadline = startedAt + Math.min(MAX_PROTECTED_REALPATH_BUDGET_MS, Math.floor(totalMs / 2));
2709
+ const installEntryKeys = /* @__PURE__ */ new Set();
2710
+ for (const raw of options.installDirs ?? []) {
2711
+ if (raw === void 0) continue;
2712
+ const normalized = normalizeWindowsPathForCompare(raw);
2713
+ if (normalized !== void 0) installEntryKeys.add(normalized.toLowerCase());
2714
+ }
2715
+ const installLexical = (options.installDirs ?? []).flatMap((raw) => collectInstallProtectedDirs(raw));
2716
+ const rawProtected = collectRawProtectedDirs([...options.protectedDirs ?? [], ...installLexical]);
2717
+ const resolvedProtected = await Promise.all(rawProtected.map((raw) => resolveProtectedDirAsync(raw, protectedDeadline, signal)));
2718
+ if (signal?.aborted) return void 0;
2719
+ const protectedDirs = [];
2720
+ const seenProtected = /* @__PURE__ */ new Set();
2721
+ const addProtected = (dir) => {
2722
+ if (dir === void 0) return;
2723
+ const key = `${dir.lexical.toLowerCase()}\0${dir.real?.toLowerCase() ?? ""}`;
2724
+ if (seenProtected.has(key)) return;
2725
+ seenProtected.add(key);
2726
+ protectedDirs.push(dir);
2727
+ };
2728
+ for (const dir of resolvedProtected) {
2729
+ addProtected(dir);
2730
+ if (dir !== void 0 && dir.real !== void 0 && installEntryKeys.has(dir.lexical.toLowerCase())) for (const canonicalAncestor of collectInstallProtectedDirs(dir.real)) addProtected({
2731
+ lexical: canonicalAncestor,
2732
+ real: canonicalAncestor
2733
+ });
2734
+ }
2735
+ const candidates = buildCandidates(protectedDirs, options.commandPath, options.preferCommandDir === true);
2736
+ let longOutsideFallback;
2737
+ let shortFallback;
2738
+ let anyFallback;
2739
+ for (const rawCandidate of candidates) {
2740
+ if (signal?.aborted || overallDeadline - Date.now() <= 0) break;
2741
+ const candidate = await resolveCandidateDirAsync(rawCandidate, overallDeadline, signal);
2742
+ if (candidate === void 0) continue;
2743
+ const chosen = preferredCandidatePath(candidate);
2744
+ const isShort = isShortWindowsSpawnPath(chosen);
2745
+ if (!protectedDirs.some((folder) => isInsideProtectedFolder(folder, candidate))) {
2746
+ if (isShort) return chosen;
2747
+ longOutsideFallback ??= chosen;
2748
+ continue;
2749
+ }
2750
+ if (isShort) shortFallback ??= chosen;
2751
+ anyFallback ??= chosen;
2752
+ }
2753
+ return longOutsideFallback ?? shortFallback ?? anyFallback;
2754
+ }
2755
+ /**
2756
+ * Pure synchronous lexical working-directory selector for kill commands (zero filesystem syscalls).
2757
+ *
2758
+ * Avoids unverified `TMP`/`TEMP` paths (which may not exist) and prefers reliable OS directories
2759
+ * (`C:\Windows` when `SystemRoot` is on `C:` or unset, or `process.cwd()`'s own drive root when Windows is
2760
+ * installed on another drive or `process.cwd()` is inside `C:\Windows`), rejecting relative paths, bare drives,
2761
+ * raw devices, incomplete UNC roots, and paths lexically inside any protected folder (including `\\?\`, `\\.\`,
2762
+ * and `\\?\UNC\` aliases). Always preserves `\\?\` / `\\?\UNC\` on paths >= 248 chars.
2763
+ */
2764
+ function resolveSafeWindowsKillCwdLexical(options = {}) {
2765
+ const protectedDirs = [];
2766
+ const installLexical = (options.installDirs ?? []).flatMap((raw) => collectInstallProtectedDirs(raw));
2767
+ for (const raw of collectRawProtectedDirs([...options.protectedDirs ?? [], ...installLexical])) {
2768
+ const lexical = normalizeWindowsPathForCompare(raw);
2769
+ if (lexical !== void 0) protectedDirs.push({
2770
+ lexical,
2771
+ real: void 0
2772
+ });
2773
+ }
2774
+ const normalizedCommand = options.commandPath === void 0 ? void 0 : normalizeWindowsPathForCompare(options.commandPath);
2775
+ const commandDir = normalizedCommand === void 0 ? void 0 : win32$1.dirname(normalizedCommand);
2776
+ const commandRoot = windowsDriveRoot(normalizedCommand);
2777
+ const protectedRoots = protectedDirs.map((folder) => windowsDriveRoot(folder.lexical));
2778
+ const systemRootDrive = windowsDriveRoot(process.env.SystemRoot)?.toLowerCase();
2779
+ const candidates = dedupeCandidates(systemRootDrive !== void 0 && systemRootDrive !== "c:\\" ? [
2780
+ ...protectedRoots,
2781
+ windowsDriveRoot(process.env.SystemRoot),
2782
+ commandRoot,
2783
+ "C:\\Windows",
2784
+ process.env.SystemRoot,
2785
+ process.env.windir,
2786
+ commandDir,
2787
+ "C:\\"
2788
+ ] : [
2789
+ "C:\\Windows",
2790
+ ...protectedRoots,
2791
+ commandDir,
2792
+ commandRoot,
2793
+ process.env.SystemRoot,
2794
+ process.env.windir,
2795
+ "C:\\"
2796
+ ]);
2797
+ let longOutsideFallback;
2798
+ let shortFallback;
2799
+ let anyFallback;
2800
+ for (const rawCandidate of candidates) {
2801
+ const lexical = normalizeWindowsPathForCompare(rawCandidate);
2802
+ if (lexical === void 0) continue;
2803
+ const candidate = {
2804
+ lexical,
2805
+ real: void 0,
2806
+ unverifiedLink: false
2807
+ };
2808
+ const chosen = toSpawnWindowsPath(lexical);
2809
+ const isShort = isShortWindowsSpawnPath(chosen);
2810
+ if (!protectedDirs.some((folder) => isInsideProtectedFolder(folder, candidate))) {
2811
+ if (isShort) return chosen;
2812
+ longOutsideFallback ??= chosen;
2813
+ continue;
2814
+ }
2815
+ if (isShort) shortFallback ??= chosen;
2816
+ anyFallback ??= chosen;
2817
+ }
2818
+ return longOutsideFallback ?? shortFallback ?? anyFallback;
2819
+ }
2820
+ // dist/utils/compile-cache-warmup-host.js
2821
+ var compile_cache_warmup_host_exports = /* @__PURE__ */ __exportAll({
2822
+ compileCacheHelperLaunch: () => compileCacheHelperLaunch,
2823
+ compileCacheWarmupRuntimes: () => compileCacheWarmupRuntimes,
2824
+ decodeCompileCacheWarmupPlan: () => decodeCompileCacheWarmupPlan,
2825
+ encodeCompileCacheWarmupPlan: () => encodeCompileCacheWarmupPlan,
2826
+ startCompileCacheHelper: () => startCompileCacheHelper,
2827
+ warmCompileCache: () => warmCompileCache
2828
+ });
2829
+ const __atomicDistModuleUrl$1 = new URL("../utils/compile-cache-warmup-host.js", import.meta.url).href;
2830
+ function encodeCompileCacheWarmupPlan(plan) {
2831
+ return Buffer.from(JSON.stringify(plan), "utf8").toString("base64url");
2832
+ }
2833
+ function decodeCompileCacheWarmupPlan(encoded) {
2834
+ if (!encoded) return {
2835
+ next: [],
2836
+ required: []
2837
+ };
2838
+ const plan = JSON.parse(Buffer.from(encoded, "base64url").toString("utf8"));
2839
+ return {
2840
+ next: plan.next ?? [],
2841
+ required: plan.required ?? []
2842
+ };
2843
+ }
2844
+ function resolveWarmupScriptPath(script) {
2845
+ if (process.platform === "win32") {
2846
+ if (isAbsoluteWindowsPath(script)) return script;
2847
+ try {
2848
+ return win32$1.resolve(process.cwd(), script);
2849
+ } catch {
2850
+ return script;
2851
+ }
2852
+ }
2853
+ return isAbsolute$1(script) ? script : resolve$1(script);
2854
+ }
2855
+ function resolveWarmupHelperCwd(resolvedScript) {
2856
+ if (process.platform !== "win32") return "/";
2857
+ const scriptDir = win32$1.dirname(resolvedScript);
2858
+ return resolveSafeWindowsKillCwdLexical({
2859
+ protectedDirs: collectInstallProtectedDirs(scriptDir),
2860
+ commandPath: process.execPath
2861
+ }) ?? windowsDriveRoot(scriptDir) ?? "C:\\";
2862
+ }
2863
+ function compileCacheHelperLaunch(runtime, buildId, script = fileURLToPath(new URL("./compile-cache-warmup.js", __atomicDistModuleUrl$1)), env = process.env, plan = {
2864
+ next: [],
2865
+ required: []
2866
+ }) {
2867
+ const helperEnv = { ...env };
2868
+ if (runtime.nodeOptions) helperEnv.NODE_OPTIONS = runtime.nodeOptions;
2869
+ else delete helperEnv.NODE_OPTIONS;
2870
+ const resolvedScript = resolveWarmupScriptPath(script);
2871
+ return {
2872
+ command: process.execPath,
2873
+ args: [
2874
+ ...runtime.execArgv,
2875
+ "--no-addons",
2876
+ resolvedScript,
2877
+ buildId,
2878
+ encodeCompileCacheWarmupPlan(plan)
2879
+ ],
2880
+ cwd: resolveWarmupHelperCwd(resolvedScript),
2881
+ env: helperEnv,
2882
+ detached: true
2883
+ };
2884
+ }
2885
+ function startCompileCacheHelper(launch) {
2886
+ const spawnWithCwd = (cwd, allowRetry) => {
2887
+ try {
2888
+ const child = spawn(launch.command, [...launch.args], {
2889
+ cwd,
2890
+ env: launch.env,
2891
+ detached: launch.detached,
2892
+ stdio: "ignore",
2893
+ windowsHide: true
2894
+ });
2895
+ child.on("error", (error) => {
2896
+ if (allowRetry && process.platform === "win32" && error.code === "ENOENT") {
2897
+ const scriptArg = launch.args[launch.args.length - 3];
2898
+ const scriptDir = scriptArg ? win32$1.dirname(resolveWarmupScriptPath(scriptArg)) : void 0;
2899
+ resolveSafeWindowsWorkingDirectoryAsync({
2900
+ installDirs: scriptDir ? [scriptDir] : void 0,
2901
+ commandPath: launch.command,
2902
+ timeoutMs: 100
2903
+ }).then((freshCwd) => {
2904
+ if (freshCwd !== void 0 && freshCwd.toLowerCase() !== cwd.toLowerCase()) spawnWithCwd(freshCwd, false);
2905
+ }).catch(() => {});
2906
+ }
2907
+ });
2908
+ child.unref();
2909
+ return true;
2910
+ } catch {
2911
+ return false;
2912
+ }
2913
+ };
2914
+ return spawnWithCwd(launch.cwd, true);
2915
+ }
2916
+ let warmupStarted = false;
2917
+ function compileCacheWarmupRuntimes(own, engineExecArgv) {
2918
+ const engine = {
2919
+ execArgv: engineExecArgv,
2920
+ nodeOptions: own.nodeOptions
2921
+ };
2922
+ if (engine.execArgv.length === own.execArgv.length && engine.execArgv.every((arg, index) => arg === own.execArgv[index])) return [own];
2923
+ const heapFlag = /^--max[-_]old[-_]space[-_]size=\d+$/;
2924
+ return own.execArgv.length === 0 && !heapFlag.test(own.nodeOptions) && engine.execArgv.length === 1 && heapFlag.test(engine.execArgv[0]) ? [own] : [engine, own];
2925
+ }
2926
+ function warmCompileCache(engineExecArgv) {
2927
+ const deferral = processCompileCacheDeferral();
2928
+ if (!deferral?.helper || warmupStarted) return;
2929
+ warmupStarted = true;
2930
+ const [first, ...next] = compileCacheWarmupRuntimes(deferral.runtime, engineExecArgv);
2931
+ startCompileCacheHelper(compileCacheHelperLaunch(first, deferral.buildId, void 0, void 0, {
2932
+ next,
2933
+ required: []
2934
+ }));
2935
+ }
2936
+ // dist/utils/interactive-engine-bootstrap.js
2937
+ /**
2938
+ * Private startup channel for the isolated interactive engine.
2939
+ *
2940
+ * The engine child needs four control values (engine role, host PID, guardian
2941
+ * path, and optionally an API key) before its runtime exists. They used to
2942
+ * travel as environment variables, which cannot be taken back: under Bun a
2943
+ * child spawned without an explicit `env` inherits the runtime's launch-time
2944
+ * environment map, so deleting the variables from `process.env` afterwards does
2945
+ * not stop arbitrary extension or hook code from leaking them — including the
2946
+ * API key — into its own subprocesses.
2947
+ *
2948
+ * The engine is therefore launched with an environment that never contained the
2949
+ * values, and the values travel in a 0600 file whose path is passed as a private
2950
+ * CLI argument. The child reads it once, freezes the snapshot, and unlinks it.
2951
+ * The filename carries no secret material.
2952
+ *
2953
+ * Cleanup is ownership-scoped. The path is untrusted child input — anyone can
2954
+ * pass the private flag — so a reader may unlink only that exact file. Only the
2955
+ * writer, which holds an {@link InteractiveEngineBootstrapHandle} for the
2956
+ * directory it created, may remove that directory recursively.
2957
+ */
2958
+ const INTERACTIVE_ENGINE_BOOTSTRAP_FLAG = "--internal-engine-bootstrap";
2959
+ /**
2960
+ * The only argument of an engine child an interactive host starts before it knows the engine's arguments: the child
2961
+ * loads the application, then reads them from its first stdin line (see engine-prewarm.ts).
2962
+ */
2963
+ const INTERACTIVE_ENGINE_PREWARM_FLAG = "--internal-engine-prewarm";
2964
+ /**
2965
+ * After the prewarm flag: the host runs `--no-session`, so the prewarmed engine opens no session database and starts no
2966
+ * thread for one. Read only at process entry; the engine's own arguments arrive later.
2967
+ */
2968
+ const INTERACTIVE_ENGINE_PREWARM_NO_DATABASE = `${INTERACTIVE_ENGINE_PREWARM_FLAG}-no-database`;
2969
+ async function writeInteractiveEngineBootstrapAsync(record) {
2970
+ const directory = await mkdtemp(join$1(tmpdir(), "atomic-engine-bootstrap-"));
2971
+ const path = join$1(directory, "bootstrap.json");
2972
+ const tempPath = `${path}.tmp`;
2973
+ const payload = {
2974
+ version: 1,
2975
+ ...record
2976
+ };
2977
+ try {
2978
+ await writeFile(tempPath, JSON.stringify(payload), {
2979
+ encoding: "utf8",
2980
+ mode: 384
2981
+ });
2982
+ await rename(tempPath, path);
2983
+ } catch (error) {
2984
+ await rm(tempPath, { force: true }).catch(() => {});
2985
+ await rm(directory, {
2986
+ recursive: true,
2987
+ force: true
2988
+ }).catch(() => {});
2989
+ throw error;
2990
+ }
2991
+ return {
2992
+ path,
2993
+ directory
2994
+ };
2995
+ }
2996
+ async function removeOwnedInteractiveEngineBootstrapAsync(handle) {
2997
+ if (!handle) return;
2998
+ await rm(handle.directory, {
2999
+ recursive: true,
3000
+ force: true
3001
+ }).catch(() => {});
3002
+ }
3003
+ /**
3004
+ * Split the private bootstrap argument out of an argv slice.
3005
+ *
3006
+ * Returns the remaining arguments so normal CLI parsing never sees the flag.
3007
+ */
3008
+ function takeInteractiveEngineBootstrapArg(args) {
3009
+ const remaining = [];
3010
+ let path;
3011
+ for (let index = 0; index < args.length; index += 1) {
3012
+ const value = args[index];
3013
+ if (value === "--internal-engine-bootstrap" && index + 1 < args.length) {
3014
+ path = args[++index];
3015
+ continue;
3016
+ }
3017
+ if (value.startsWith(`--internal-engine-bootstrap=`)) {
3018
+ path = value.slice(28);
3019
+ continue;
3020
+ }
3021
+ remaining.push(value);
3022
+ }
3023
+ return {
3024
+ args: remaining,
3025
+ path
3026
+ };
3027
+ }
3028
+ /** True when this argv belongs to an isolated interactive engine child. */
3029
+ function hasInteractiveEngineBootstrapArg(args) {
3030
+ return takeInteractiveEngineBootstrapArg(args).path !== void 0;
3031
+ }
3032
+ /**
3033
+ * Read and consume a bootstrap record.
3034
+ *
3035
+ * The named file is always unlinked, including on malformed content, so a stale
3036
+ * API key never outlives the handshake. The path came from argv, so nothing
3037
+ * around it is touched: no parent directory, no sibling.
3038
+ */
3039
+ function readInteractiveEngineBootstrap(path) {
3040
+ let raw;
3041
+ try {
3042
+ raw = readFileSync$1(path, "utf8");
3043
+ } catch {
3044
+ return;
3045
+ } finally {
3046
+ rmSync$1(path, { force: true });
3047
+ }
3048
+ try {
3049
+ const parsed = JSON.parse(raw);
3050
+ if (parsed.version !== 1) return void 0;
3051
+ if (typeof parsed.hostPid !== "number" || typeof parsed.guardFile !== "string") return void 0;
3052
+ const trustDecisions = readTrustDecisions(parsed.trustDecisions);
3053
+ const startupExtensionCheck = readStartupExtensionCheck(parsed.startupExtensionCheck);
3054
+ return {
3055
+ version: parsed.version,
3056
+ hostPid: parsed.hostPid,
3057
+ guardFile: parsed.guardFile,
3058
+ ...typeof parsed.apiKey === "string" ? { apiKey: parsed.apiKey } : {},
3059
+ ...trustDecisions ? { trustDecisions } : {},
3060
+ ...parsed.projectResourceWithdrawals === true ? { projectResourceWithdrawals: true } : {},
3061
+ ...startupExtensionCheck ? { startupExtensionCheck } : {},
3062
+ ...parsed.queuedDeliveries === true ? { queuedDeliveries: true } : {},
3063
+ ...typeof parsed.startedSessionId === "string" ? { startedSessionId: parsed.startedSessionId } : {},
3064
+ ...parsed.restarted === true ? { restarted: true } : {}
3065
+ };
3066
+ } catch {
3067
+ return;
3068
+ }
3069
+ }
3070
+ /** The host's startup extension check of a bootstrap record, or undefined when it is missing or malformed. */
3071
+ function readStartupExtensionCheck(value) {
3072
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return void 0;
3073
+ const { cwd, extensionsCanDecide } = value;
3074
+ return typeof cwd === "string" && typeof extensionsCanDecide === "boolean" ? {
3075
+ cwd,
3076
+ extensionsCanDecide
3077
+ } : void 0;
3078
+ }
3079
+ /** The trust decisions of a bootstrap record: only true or false values by path; anything else is left out. */
3080
+ function readTrustDecisions(value) {
3081
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return void 0;
3082
+ const record = value;
3083
+ const decisions = {
3084
+ projects: readDecisions(record.projects),
3085
+ extensionSources: readDecisions(record.extensionSources)
3086
+ };
3087
+ return Object.keys(decisions.projects).length + Object.keys(decisions.extensionSources).length > 0 ? decisions : void 0;
3088
+ }
3089
+ function readDecisions(value) {
3090
+ const decisions = {};
3091
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return decisions;
3092
+ for (const [path, trusted] of Object.entries(value)) if (typeof trusted === "boolean") decisions[path] = trusted;
3093
+ return decisions;
3094
+ }
3095
+ // dist/utils/heap-relaunch.js
3096
+ const HEAP_RELAUNCHED_ENV = "ATOMIC_INTERNAL_HEAP_RELAUNCHED";
3097
+ /** Mirrors `resolveAppMode`: rpc, json and print modes, including print selected by piped input or output. */
3098
+ function isHeadlessInvocation(args, terminal) {
3099
+ if (args.includes("--internal-engine-bootstrap") || args.includes("--help") || args.includes("-h")) return false;
3100
+ return args.some((arg, index) => arg === "-p" || arg === "--print" || arg === "--mode" && ["json", "rpc"].includes(args[index + 1] ?? "")) || !terminal.stdinIsTTY || !terminal.stdoutIsTTY;
3101
+ }
3102
+ /**
3103
+ * Heap flags a headless run on Node should be relaunched with, or none. Interactive sessions size their engine
3104
+ * child instead, and a process that was already relaunched or started with an explicit heap size keeps its own.
3105
+ */
3106
+ function headlessHeapRelaunchArgs(args) {
3107
+ const terminal = {
3108
+ stdinIsTTY: process.stdin.isTTY === true,
3109
+ stdoutIsTTY: process.stdout.isTTY === true
3110
+ };
3111
+ if (process.env[HEAP_RELAUNCHED_ENV] !== void 0) {
3112
+ delete process.env[HEAP_RELAUNCHED_ENV];
3113
+ return [];
3114
+ }
3115
+ if (!isHeadlessInvocation(args, terminal) || commandLineSetsHeapSize(process.execArgv)) return [];
3116
+ if ("bun" in process.versions) return [];
3117
+ return engineHeapRuntimeArgs({
3118
+ runsOnNode: true,
3119
+ totalMemoryBytes: totalmem(),
3120
+ constrainedMemoryBytes: process.constrainedMemory(),
3121
+ currentHeapLimitBytes: getHeapStatistics().heap_size_limit,
3122
+ nodeOptions: process.env.NODE_OPTIONS,
3123
+ execArgv: [],
3124
+ configuredHeapMb: getEnvValue(ENV_HEAP_MB)
3125
+ });
3126
+ }
3127
+ /** Runs this CLI again with the heap flags, passing through stdio, termination signals and the exit status. */
3128
+ function relaunchWithHeap(heapArgs, args) {
3129
+ const child = spawn(process.execPath, [
3130
+ ...heapArgs,
3131
+ ...process.execArgv,
3132
+ process.argv[1],
3133
+ ...args
3134
+ ], {
3135
+ stdio: "inherit",
3136
+ env: {
3137
+ ...process.env,
3138
+ [HEAP_RELAUNCHED_ENV]: "1"
3139
+ }
3140
+ });
3141
+ for (const signal of [
3142
+ "SIGINT",
3143
+ "SIGTERM",
3144
+ "SIGHUP"
3145
+ ]) process.on(signal, () => child.kill(signal));
3146
+ child.on("error", (error) => {
3147
+ process.stderr.write(`Failed to start Atomic with a larger heap: ${error.message}\n`);
3148
+ process.exit(1);
3149
+ });
3150
+ child.on("exit", (code, signal) => {
3151
+ if (signal) {
3152
+ process.removeAllListeners(signal);
3153
+ process.kill(process.pid, signal);
3154
+ return;
3155
+ }
3156
+ process.exit(code ?? 1);
3157
+ });
3158
+ }
3159
+ // dist/utils/module-require.js
3160
+ /**
3161
+ * createRequire anchored so bare-specifier resolution works in every runtime.
3162
+ *
3163
+ * In the compiled binary the bundle is CJS (bytecode), where import.meta.url
3164
+ * is rewritten to the original build-machine source path; requiring through it
3165
+ * would resolve node_modules against paths that do not exist on user machines.
3166
+ * Anchor to the executable instead so resolution walks from the node_modules
3167
+ * shipped next to the binary.
3168
+ */
3169
+ function createModuleRequire(moduleUrl) {
3170
+ return createRequire(resolutionBaseUrl(moduleUrl));
3171
+ }
3172
+ /**
3173
+ * A resolution base URL safe for the current runtime.
3174
+ *
3175
+ * In compiled binaries (monolithic bun or the Atomic split launcher) the
3176
+ * bundled `import.meta.url` is the build machine's source URL — a foreign-OS
3177
+ * `file://` URL that `fileURLToPath` rejects on other platforms (notably a
3178
+ * macOS `file:///Users/...` URL on Windows). Any API that decodes the base
3179
+ * (`createRequire`, jiti's `createJiti`) then throws `ERR_INVALID_FILE_URL_PATH`.
3180
+ * Anchor to the executable instead, which is always a valid local file URL.
3181
+ */
3182
+ function resolutionBaseUrl(moduleUrl) {
3183
+ return isBunBinary ? pathToFileURL(process.execPath).href : moduleUrl;
3184
+ }
3185
+ // dist/utils/inherited-hangup.js
3186
+ const __atomicDistModuleUrl = new URL("../utils/inherited-hangup.js", import.meta.url).href;
3187
+ let hangupIgnored = false;
3188
+ function noteInheritedHangup() {
3189
+ if (process.platform === "win32" || !("bun" in process.versions)) return;
3190
+ try {
3191
+ hangupIgnored = createModuleRequire(__atomicDistModuleUrl)("@bastani/atomic-natives").signalIgnored?.(constants$1.signals.SIGHUP) === true;
3192
+ } catch {}
3193
+ if (hangupIgnored) process.on("SIGHUP", () => {});
3194
+ }
3195
+ function startedWithHangupIgnored() {
3196
+ return hangupIgnored;
3197
+ }
3198
+ // dist/utils/interactive-invocation.js
3199
+ /** Options and arguments that start something other than the plain interactive session, which has no engine. */
3200
+ const NON_INTERACTIVE_FLAGS = /* @__PURE__ */ new Set([
3201
+ "-p",
3202
+ "--print",
3203
+ "--mode",
3204
+ "-h",
3205
+ "--help",
3206
+ "-v",
3207
+ "--version",
3208
+ "--export",
3209
+ "--list-models"
3210
+ ]);
3211
+ /**
3212
+ * Whether these arguments start the plain interactive session: a terminal on both ends and arguments that are only
3213
+ * options (a subcommand or a prompt argument is never one), none of which selects another mode.
3214
+ */
3215
+ function isPlainInteractiveSessionInvocation(args, terminal) {
3216
+ if (!terminal.stdinIsTTY || !terminal.stdoutIsTTY) return false;
3217
+ if (args.length > 0 && !args[0].startsWith("-")) return false;
3218
+ return !args.some((arg) => NON_INTERACTIVE_FLAGS.has(arg) || arg.startsWith("--internal-"));
3219
+ }
3220
+ // dist/utils/startup-prefetch.js
3221
+ /** Options that make Node run code of the user's in every process it starts: a preload or a module loader. */
3222
+ const USER_CODE_OPTIONS = /* @__PURE__ */ new Set([
3223
+ "--require",
3224
+ "-r",
3225
+ "--import",
3226
+ "--loader",
3227
+ "--experimental-loader"
3228
+ ]);
3229
+ /**
3230
+ * Reads the startup's files with this many in flight, on the reader process's own I/O pool, never this process's: four
3231
+ * per CPU, from 4 to 32, so that on a machine with few CPUs the reader leaves them to Atomic's own start.
3232
+ */
3233
+ function readerThreads() {
3234
+ return String(Math.min(32, Math.max(4, 4 * availableParallelism())));
3235
+ }
3236
+ /**
3237
+ * The record, in the agent directory, that a reader read this installation's startup files (or found them already in
3238
+ * memory) since the machine last started: `startup-prefetch-reader.ts` writes it.
3239
+ */
3240
+ const STARTUP_FILES_READ_MARKER = "startup-files-read.json";
3241
+ /** How far two readings of when the machine last started may differ and still name the same start. */
3242
+ const BOOT_TIME_TOLERANCE_MS = 1e4;
3243
+ /** When the machine last started, from how long it has been running; the system clock moving changes it. */
3244
+ function machineStartTimeMs() {
3245
+ return Date.now() - uptime() * 1e3;
3246
+ }
3247
+ /**
3248
+ * Whether a marker says this installation's startup files were read since the machine last started: its version, its
3249
+ * installation and that start. A missing, unreadable or other marker says no.
3250
+ */
3251
+ function startupFilesReadThisStart(marker, version, install, startTimeMs) {
3252
+ if (marker === void 0) return false;
3253
+ try {
3254
+ const read = JSON.parse(marker);
3255
+ return read.version === version && read.install === install && typeof read.bootTimeMs === "number" && Math.abs(read.bootTimeMs - startTimeMs) <= BOOT_TIME_TOLERANCE_MS;
3256
+ } catch {
3257
+ return false;
3258
+ }
3259
+ }
3260
+ /**
3261
+ * Starts a short-lived process that reads the files this interactive session is about to load, many at once
3262
+ * (`startup-prefetch-reader.ts`). On a cold start an antivirus scans each file when it is first opened, and the module
3263
+ * loader opens them one at a time; read ahead in parallel, they are scanned in parallel. The reader only reads, ends
3264
+ * when it is done, and ends with this process if this process ends first. Once it has read them (or found them in
3265
+ * memory), it records so in the agent directory, and later starts until the machine restarts start no reader for this
3266
+ * installation and version. Nothing starts in the standalone binary
3267
+ * (one file), without the file list the build writes, when the package directory is overridden (it then names assets,
3268
+ * not this installation's code), when the user sets Node's I/O pool size, or when the process runs a preload, a module
3269
+ * loader or the permission model.
3270
+ */
3271
+ function resolveAgainstWindowsCallerCwd(rawPath) {
3272
+ if (isAbsoluteWindowsPath(rawPath)) return rawPath;
3273
+ try {
3274
+ return win32$1.resolve(process.cwd(), rawPath);
3275
+ } catch {
3276
+ return rawPath;
3277
+ }
3278
+ }
3279
+ function startStartupPrefetch(packageDir) {
3280
+ if (process.platform !== "win32" || process.versions.bun !== void 0 || isBunBinary) return;
3281
+ if (process.permission !== void 0 || process.env.ATOMIC_PACKAGE_DIR || process.env.PI_PACKAGE_DIR) return;
3282
+ if (process.env.UV_THREADPOOL_SIZE !== void 0) return;
3283
+ if (startupNodeOptions().some((option) => USER_CODE_OPTIONS.has(option.name))) return;
3284
+ const resolvedPackageDir = resolveAgainstWindowsCallerCwd(packageDir);
3285
+ const listPath = win32$1.join(resolvedPackageDir, "dist", "startup-files.json");
3286
+ const readerPath = win32$1.join(resolvedPackageDir, "dist", "utils", "startup-prefetch-reader.js");
3287
+ if (!existsSync$1(listPath) || !existsSync$1(readerPath)) return;
3288
+ const resolvedAgentDir = resolveAgainstWindowsCallerCwd(getAgentDir());
3289
+ const marker = win32$1.join(resolvedAgentDir, STARTUP_FILES_READ_MARKER);
3290
+ let markerText;
3291
+ try {
3292
+ markerText = readFileSync$1(marker, "utf8");
3293
+ } catch {}
3294
+ if (startupFilesReadThisStart(markerText, VERSION, resolvedPackageDir, machineStartTimeMs())) return;
3295
+ try {
3296
+ const readerCwd = resolveSafeWindowsKillCwdLexical({
3297
+ installDirs: [resolvedPackageDir],
3298
+ protectedDirs: [resolvedAgentDir],
3299
+ commandPath: process.execPath
3300
+ }) ?? windowsDriveRoot(resolvedPackageDir) ?? "C:\\";
3301
+ const reader = spawn(process.execPath, [
3302
+ readerPath,
3303
+ listPath,
3304
+ resolvedPackageDir,
3305
+ marker,
3306
+ VERSION
3307
+ ], {
3308
+ cwd: readerCwd,
3309
+ stdio: [
3310
+ "pipe",
3311
+ "ignore",
3312
+ "ignore"
3313
+ ],
3314
+ windowsHide: true,
3315
+ env: {
3316
+ ...process.env,
3317
+ UV_THREADPOOL_SIZE: readerThreads(),
3318
+ NODE_OPTIONS: ""
3319
+ }
3320
+ });
3321
+ try {
3322
+ if (reader.pid !== void 0) setPriority(reader.pid, constants$1.priority.PRIORITY_BELOW_NORMAL);
3323
+ } catch {}
3324
+ reader.on("error", () => {});
3325
+ reader.stdin?.on("error", () => {});
3326
+ reader.unref();
3327
+ reader.stdin?.unref?.();
3328
+ const stop = () => {
3329
+ if (reader.exitCode === null && reader.signalCode === null) reader.kill();
3330
+ };
3331
+ process.once("exit", stop);
3332
+ reader.once("close", () => process.off("exit", stop));
3333
+ } catch {}
3334
+ }
3335
+ // dist/utils/updated-install.js
3336
+ /**
3337
+ * A running process keeps every module it has loaded and loads the rest on demand from the installation on disk. An
3338
+ * in-place update (`npm install -g` or `bun add -g` of a new version over this one) replaces those files while the
3339
+ * process runs: a newer file that names an export the copy this process loaded lacks fails to link, and a file the
3340
+ * update removed is gone. Neither can succeed until the process restarts, so code loaded on demand reports them as such.
3341
+ * A module of anything else, such as a user's extension, that cannot load keeps its own error: a restart would not
3342
+ * change it.
3343
+ */
3344
+ /** A feature whose code could not load because the installation changed under this process. */
3345
+ var UpdatedInstallError = class extends Error {
3346
+ feature;
3347
+ constructor(message, feature, cause) {
3348
+ super(message, { cause });
3349
+ this.name = "UpdatedInstallError";
3350
+ this.feature = feature;
3351
+ }
3352
+ };
3353
+ /** Node's and Bun's link errors: an import names an export its dependency lacks. */
3354
+ const LINK_FAILURE = /does not provide an export named|Export named '[^']*' not found in module|Named export '[^']*' not found|^export '[^']*' not found in '/;
3355
+ const LOAD_FAILURE_CODES = /* @__PURE__ */ new Set([
3356
+ "ERR_MODULE_NOT_FOUND",
3357
+ "MODULE_NOT_FOUND",
3358
+ "ERR_PACKAGE_PATH_NOT_EXPORTED"
3359
+ ]);
3360
+ /**
3361
+ * Bun, for a module file that went away after it read the file's directory: a `BuildMessage` with no code, naming the
3362
+ * file it could not read.
3363
+ */
3364
+ const BUN_MISSING_FILE = /^ENOENT reading "(.+)"$/;
3365
+ /** Atomic's own packages, by name or installed (a package manager that hoists dependencies, Bun, puts them beside it). */
3366
+ const OWN_PACKAGE = /^@bastani\/atomic(?:-(?:ai|tui|agent-core|codemode|schema|telemetry|natives))?(?:\/|$)|[\\/]node_modules[\\/]@bastani[\\/]atomic(?:-(?:ai|tui|agent-core|codemode|schema|telemetry|natives))?[\\/]/;
3367
+ /**
3368
+ * Whether `error` is the runtime failing to load a module: one that names an export its dependency lacks (Node and Bun
3369
+ * report a `SyntaxError` when they link it), or one that is not there (a removed file, package or package export).
3370
+ */
3371
+ function isModuleLoadFailure(error) {
3372
+ if (typeof error !== "object" || error === null) return false;
3373
+ const { code, message, name } = error;
3374
+ if (typeof code === "string" && LOAD_FAILURE_CODES.has(code)) return true;
3375
+ if (name === "BuildMessage" && typeof message === "string" && BUN_MISSING_FILE.test(message)) return true;
3376
+ return error instanceof SyntaxError && typeof message === "string" && LINK_FAILURE.test(message);
3377
+ }
3378
+ /** The module `request` names when `importer` asks for it: a file path, or the package name of a bare request. */
3379
+ function requested(request, importer) {
3380
+ if (!request.startsWith(".") && !request.startsWith("/") && !request.startsWith("file:") && !isAbsolute$1(request)) return OWN_PACKAGE.test(request) || importer === void 0 ? request : importer;
3381
+ if (request.startsWith("file:") || isAbsolute$1(request)) return request;
3382
+ if (importer === void 0) return request;
3383
+ const from = importer.startsWith("file:") ? fileURLToPath(importer) : importer;
3384
+ return resolve$1(dirname$1(from), request);
3385
+ }
3386
+ /**
3387
+ * Whose module could not load, as the error tells it: the missing file itself, the package a module asked for (or,
3388
+ * for a package that is not Atomic's own, the module that asked), or the module whose import fails to link (Bun names
3389
+ * the module that lacks the export instead). Undefined when the error does not say.
3390
+ */
3391
+ function failedLoadLocation(error) {
3392
+ const message = typeof error.message === "string" ? error.message : "";
3393
+ if (typeof error.url === "string") return error.url;
3394
+ if (error.name === "BuildMessage") return BUN_MISSING_FILE.exec(message)?.[1];
3395
+ if (typeof error.referrer === "string" && typeof error.specifier === "string") return requested(error.specifier, error.referrer);
3396
+ if (Array.isArray(error.requireStack)) {
3397
+ const request = /Cannot find module '([^']+)'/.exec(message)?.[1];
3398
+ const importer = typeof error.requireStack[0] === "string" ? error.requireStack[0] : void 0;
3399
+ return request === void 0 ? importer : requested(request, importer);
3400
+ }
3401
+ const exportsMap = / is not defined by "exports" in (.+?package\.json)/.exec(message)?.[1];
3402
+ if (exportsMap !== void 0) return exportsMap;
3403
+ const missing = /Cannot find (?:module|package) '([^']+)' imported from (.+)$/m.exec(message);
3404
+ if (missing) return requested(missing[1], missing[2]);
3405
+ const linking = typeof error.stack === "string" ? /^(file:\/\/\S+?):\d+$/m.exec(error.stack)?.[1] : void 0;
3406
+ if (linking !== void 0) return linking;
3407
+ return /not found in module '([^']+)'|^export '[^']*' not found in '([^']+)'/.exec(message)?.slice(1).find(Boolean);
3408
+ }
3409
+ /** Whether `location`, a path, a file URL or a package name, is part of the installation this process runs from. */
3410
+ function partOfInstallation(location) {
3411
+ if (OWN_PACKAGE.test(location)) return true;
3412
+ let path;
3413
+ try {
3414
+ path = location.startsWith("file:") ? fileURLToPath(location) : location;
3415
+ } catch {
3416
+ return false;
3417
+ }
3418
+ if (!isAbsolute$1(path)) return false;
3419
+ const inside = relative$1(getPackageDir(), resolve$1(path));
3420
+ return inside !== "" && !inside.startsWith("..") && !isAbsolute$1(inside);
3421
+ }
3422
+ /** Whether `error` is a module of the installation that could not load (see {@link isModuleLoadFailure}). */
3423
+ function isInstallationLoadFailure(error) {
3424
+ if (!isModuleLoadFailure(error)) return false;
3425
+ const location = failedLoadLocation(error);
3426
+ return location !== void 0 && partOfInstallation(location);
3427
+ }
3428
+ /**
3429
+ * What a failed on-demand load of `feature` says when `change` happened to the installation since this process
3430
+ * started: that it needs a restart, then the runtime's error. Undefined when the failure is not a module of the
3431
+ * installation that could not load, or the installation did not change.
3432
+ */
3433
+ function updatedInstallMessage(error, feature, change) {
3434
+ if (change === void 0 || !isInstallationLoadFailure(error)) return void 0;
3435
+ const restart = change.kind === "updated" ? `${APP_NAME} was updated to ${change.version} while this session was running; restart it to keep using ${feature}.` : `The ${APP_NAME} installation this session runs from was removed or replaced; restart it to keep using ${feature}.`;
3436
+ const { message } = error;
3437
+ return typeof message === "string" && message !== "" ? `${restart}\n${message}` : restart;
3438
+ }
3439
+ const CALL_SITE_RESTART = Symbol.for("atomic.on-demand-restart.v1");
3440
+ /** What `error` carries as a call-site guard's restart error; undefined for any other error. */
3441
+ function callSiteRestart(error) {
3442
+ if (typeof error !== "object" || error === null) return void 0;
3443
+ const restart = error[CALL_SITE_RESTART];
3444
+ return typeof restart?.application === "string" && typeof restart.updatedTo === "string" && typeof restart.feature === "string" ? {
3445
+ application: restart.application,
3446
+ updatedTo: restart.updatedTo,
3447
+ feature: restart.feature
3448
+ } : void 0;
3449
+ }
3450
+ /**
3451
+ * The {@link UpdatedInstallError} a failed on-demand load of `feature` becomes when it failed because an update replaced
3452
+ * the installation under this process; undefined when it failed for any other reason. A call-site guard inside the
3453
+ * load already said so; the message then names `feature`, which the guard could only name by the module it loaded.
3454
+ */
3455
+ async function updatedInstallError(error, feature) {
3456
+ if (error instanceof UpdatedInstallError) return error;
3457
+ const restart = callSiteRestart(error);
3458
+ if (restart !== void 0) {
3459
+ const cause = error.cause ?? error;
3460
+ const failure = cause.message;
3461
+ const text = `${restart.application} was updated to ${restart.updatedTo} while this session was running; restart it to keep using ${feature}.`;
3462
+ return new UpdatedInstallError(typeof failure === "string" && failure !== "" ? `${text}\n${failure}` : text, feature, cause);
3463
+ }
3464
+ if (!isInstallationLoadFailure(error)) return void 0;
3465
+ const message = updatedInstallMessage(error, feature, await detectInstallChangeAsync());
3466
+ return message === void 0 ? void 0 : new UpdatedInstallError(message, feature, error);
3467
+ }
3468
+ /**
3469
+ * Run `load`, which loads code of `feature` on demand (directly or anywhere inside it). A module of the installation
3470
+ * that cannot load because an update replaced the installation while this process runs rejects with an
3471
+ * {@link UpdatedInstallError} naming `feature`; every other outcome is `load`'s own.
3472
+ */
3473
+ async function loadOnDemand(feature, load) {
3474
+ try {
3475
+ return await load();
3476
+ } catch (error) {
3477
+ throw await updatedInstallError(error, feature) ?? error;
3478
+ }
3479
+ }
3480
+ export { APP_NAME, APP_TITLE, ATOMIC_AI_AGENT, BLUEPRINT_FILE_NAME, BUILTIN_PACKAGE_DIR_NAMES, CHANGELOG_URL, COMPILE_CACHE_ENGINE_MATCH_HOST_ENV, COMPILE_CACHE_ENGINE_WARMUP_ENV, CONFIG_DIR_NAME, CONFIG_DIR_NAMES, DebugConfigError, DebugError, DebugLogUnwritableError, DiagnosticWriter, ENV_AGENT_DIR, ENV_CLEAR_ON_SHRINK, ENV_CLIPBOARD_OSC52, ENV_CODEMODE_MAX_WORKERS, ENV_DEBUG, ENV_HARDWARE_CURSOR, ENV_HEAP_MB, ENV_MODEL_CATALOG_URL, ENV_OFFLINE, ENV_PACKAGE_DIR, ENV_SELF_UPDATE_COMMAND, ENV_SESSION_DIR, ENV_SHARE_VIEWER_URL, ENV_SKIP_VERSION_CHECK, ENV_STARTUP_BENCHMARK, ENV_STDIN_TIMEOUT_MS, ENV_TELEMETRY, ENV_TIMING, INSTALLED_EXTENSION_ENTRIES, INTERACTIVE_ENGINE_BOOTSTRAP_FLAG, INTERACTIVE_ENGINE_PREWARM_FLAG, INTERACTIVE_ENGINE_PREWARM_NO_DATABASE, LEGACY_CONFIG_DIR_NAME, LEGACY_ENV_PREFIX, NATIVES_VERSION, PACKAGE_NAME, SOURCE_EXTENSION_ENTRIES, UpdatedInstallError, VERSION, VERSION_ADOPTION_ENDPOINT, addHostStorageAdapter, canonicalizePath$1 as canonicalizePath, canonicalizePathAsync$1 as canonicalizePathAsync, compileCacheDeferral, compileCacheHelperLaunch, compileCacheWarmupRuntimes, compile_cache_warmup_host_exports, createChildProcessEnvironment, createModuleRequire, createSessionCwdMatcher, createSessionCwdMatcherAsync$1 as createSessionCwdMatcherAsync, decodeCompileCacheWarmupPlan, detectInstallChange, detectInstallChangeAsync, detectInstallMethod, enablePersistentCompileCache, encodeCompileCacheWarmupPlan, engineCompileCacheMatchHostEnv, engineCompileCacheWarmupEnv, engineHeapRuntimeArgsForHost, expandTildePath, findHelperExecutable, findHelperExecutableAsync, flushLifecycleTraceAtQuit, flushPersistentCompileCache, formatPathRelativeToCwdOrAbsolute, getAgentConfigPaths, getAgentDir, getAgentDirs, getAuthPath, getBinDir, getBlueprintActionsDir, getBundledInteractiveAssetPath, getBundledInteractiveAssetPathAsync, getChangelogPath, getCodemodeWorkerUrl, getCodemodeWorkerUrlAsync, getConfiguredSelfUpdateArgv, getCustomThemesDir, getCwdRelativePath, getDebugLogPath, getDocsPath, getEnvNames, getEnvValue, getExamplesPath, getExportTemplateDir, getExportTemplateDirAsync, getExtensionTranspileCacheDir, getGlobalBlueprintPath, getHomeDir, getInteractiveAssetsDir, getLegacyAgentDir, getModelsConfigPaths, getModelsPath, getPackageDir, getPackageJsonPath, getPathComparisonKey, getProjectBlueprintPath, getProjectConfigDirs, getProjectConfigPaths, getPromptsDir, getQuickJSWasmPath, getReadmePath, getSelfUpdateCommand, getSelfUpdateUnavailableInstruction, getSessionsDir, getSettingsPath, getShareViewerUrl, getThemesDir, getToolsDir, getUpdateInstruction, getUserConfigDirs, getUserConfigPaths, hasEnvValue, hasInteractiveEngineBootstrapArg, headlessHeapRelaunchArgs, helperLaunch, helperLaunchAsync, hostStorageAdapter, inheritsDebugSetting, installLifecycleTraceFromEnv, isBunBinary, isBunRuntime, isBundledBuild, isChildProcessExitStatusUnknownError, isDebugConfigError, isDebugError, isDebugLogUnwritableError, isDebugSettingOn, isHeadlessInvocation, isLifecycleTimingEnabled, isLocalPath, isModuleLoadFailure, isPathWithin, isPlainInteractiveSessionInvocation, loadOnDemand, makeConfiguredSelfUpdateCommand, markLifecycleTiming, markNativeContainedChild, markPathIgnoredByCloudSync, missingHelperOptions, moduleDirFromMetaUrl, normalizePath, noteInheritedHangup, onDebugSettingChange, pathsEqual, processCompileCacheDeferral, processLaunch, processLaunchAsync, readInteractiveEngineBootstrap, rehydrateDebugError, relaunchWithHeap, releaseRetainedWindowsProcessExitHandle, removeOwnedInteractiveEngineBootstrapAsync, require_cross_spawn, requiredEntriesForBuiltin, resolutionBaseUrl, resolvePath, resolveSafeWindowsKillCwdLexical, resolveSafeWindowsWorkingDirectoryAsync, retainWindowsProcessExitHandle, serializeDebugError, setDebugSetting, setEnvValue, shortenHomePath, spawnLaunchedProcess, spawnLaunchedProcessSync, spawnProcess, splitBom, startCompileCacheHelper, startStartupPrefetch, startedWithHangupIgnored, stripBom, takeInteractiveEngineBootstrapArg, updatedInstallError, waitForChildProcess, warmCompileCache, writeInteractiveEngineBootstrapAsync };
3481
+
3482
+ //# sourceMappingURL=p0-cli-BB45ZQY6.js.map