@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
@@ -1,8 +1,7 @@
1
1
  import { spawn } from "child_process";
2
- import { randomUUID } from "crypto";
3
2
  import { closeSync, existsSync, openSync, readFileSync, readSync, statSync, unlinkSync, writeFileSync } from "fs";
4
- import { appendFile, chmod, type FileHandle, mkdir, open, readFile, unlink, writeFile } from "node:fs/promises";
5
- import { basename, dirname, join } from "path";
3
+ import { access, appendFile, chmod, type FileHandle, lstat, mkdir, open, readFile, stat, unlink, writeFile } from "node:fs/promises";
4
+ import { basename, dirname, isAbsolute, join, resolve, win32 } from "path";
6
5
  import { fileURLToPath } from "url";
7
6
  import { createRequire } from "module";
8
7
  import { isSocketAnswering } from "./socket-liveness.js";
@@ -31,7 +30,6 @@ import {
31
30
  recognisedProcessStart,
32
31
  type AnnouncedBroker,
33
32
  type BrokerStartAnnouncement,
34
- readBrokerStartAnnouncementAsync,
35
33
  } from "./start-announcement.js";
36
34
  import {
37
35
  createChildProcessEnvironment,
@@ -49,6 +47,7 @@ import {
49
47
  laterProcessProbe,
50
48
  nativeProcessCreationTime,
51
49
  processStartToken,
50
+ readProcessCreationTime,
52
51
  readProcessStartToken,
53
52
  readProcessStartWithoutProcess,
54
53
  stopWindowsProcess,
@@ -59,14 +58,23 @@ import { BROKER_CONTROL_TIMEOUT_MS, controlRequest } from "./control-request.js"
59
58
  import { BROKER_PROTOCOL, type BrokerProtocolRange, decideBrokerProtocol, protocolRangeOf } from "./protocol-version.js";
60
59
  import { readSharedStorageSettingAsync, sharedStorageDigest } from "./shared-storage-setting.js";
61
60
  import {
61
+ BROKER_SOCKET_PATH_ENV,
62
62
  BROKER_STORAGE_ENV,
63
- getBrokerStartAnnouncementPath,
63
+ directBrokerSocketPath,
64
+ getAgentDir,
65
+ getAgentDirFromEnv,
64
66
  getBrokerLogPath,
65
67
  getBrokerPidPath,
66
68
  getBrokerSocketPathAsync,
67
69
  getBrokerSpawnLockPath,
68
70
  getIntercomDirPath,
69
71
  } from "./paths.js";
72
+ import {
73
+ isAbsoluteWindowsPath,
74
+ resolveSafeWindowsWorkingDirectoryAsync,
75
+ resolveSafeWindowsWorkingDirectorySync,
76
+ windowsDriveRoot,
77
+ } from "./windows-cwd.js";
70
78
  import { pathExists } from "../path-exists.js";
71
79
 
72
80
 
@@ -77,13 +85,19 @@ export function resolveIntercomPackageRoot(moduleHref: string): string {
77
85
  }
78
86
 
79
87
  export function resolveBrokerEntrypoint(packageRoot: string): string {
80
- const bundled = join(packageRoot, "broker", "broker.bundle.mjs");
81
- return existsSync(bundled) ? bundled : join(packageRoot, "broker", "broker.ts");
88
+ const root = resolveAgainstCallerCwd(packageRoot);
89
+ const bundled = process.platform === "win32" ? win32.join(root, "broker", "broker.bundle.mjs") : join(root, "broker", "broker.bundle.mjs");
90
+ return existsSync(bundled) ? bundled : process.platform === "win32" ? win32.join(root, "broker", "broker.ts") : join(root, "broker", "broker.ts");
82
91
  }
83
92
 
84
93
  export async function resolveBrokerEntrypointAsync(packageRoot: string): Promise<string> {
85
- const bundled = join(packageRoot, "broker", "broker.bundle.mjs");
86
- return (await pathExists(bundled)) ? bundled : join(packageRoot, "broker", "broker.ts");
94
+ const root = resolveAgainstCallerCwd(packageRoot);
95
+ const bundled = process.platform === "win32" ? win32.join(root, "broker", "broker.bundle.mjs") : join(root, "broker", "broker.bundle.mjs");
96
+ return (await pathExists(bundled))
97
+ ? bundled
98
+ : process.platform === "win32"
99
+ ? win32.join(root, "broker", "broker.ts")
100
+ : join(root, "broker", "broker.ts");
87
101
  }
88
102
 
89
103
 
@@ -117,20 +131,21 @@ export const BROKER_SPAWN_LOCK_MAX_AGE_MS = 60_000;
117
131
  type BrokerRuntime = "node" | "bun-source" | "bun-binary";
118
132
 
119
133
  export const INTERNAL_INTERCOM_BROKER_ARG = "--atomic-internal-intercom-broker";
120
-
121
- type BrokerLaunchSpec =
122
- | {
123
- kind: "direct";
124
- command: string;
125
- args: string[];
126
- }
127
- | {
128
- kind: "windows-launcher";
129
- command: string;
130
- args: string[];
131
- launcherPath: string;
132
- launcherCommandLine: string;
133
- };
134
+ const INTERNAL_INTERCOM_BROKER_RELAY_ARG = "--atomic-internal-intercom-broker-relay";
135
+ const INTERNAL_INTERCOM_BROKER_RELAY_CAPABILITY = Symbol.for("@bastani/atomic/intercom-broker-relay@1");
136
+
137
+ export interface BrokerLaunchSpec {
138
+ readonly kind: "direct";
139
+ readonly command: string;
140
+ readonly args: string[];
141
+ /** Windows: pass `args` verbatim without re-quoting (used only when a custom `brokerCommand` is a `.cmd`/`.bat` script). */
142
+ readonly verbatimArguments?: true;
143
+ /**
144
+ * Windows: start with `CREATE_NO_WINDOW` instead of `DETACHED_PROCESS` so a custom `brokerCommand` override
145
+ * (`.cmd`/`.bat` or wrapper `.exe`) receives a hidden windowless console inherited by any console child it spawns.
146
+ */
147
+ readonly noWindow?: true;
148
+ }
134
149
 
135
150
  function sleep(ms: number, signal?: AbortSignal): Promise<void> {
136
151
  return new Promise((resolve) => {
@@ -155,11 +170,14 @@ function requireFromExtensionDir(extensionDir: string): NodeJS.Require {
155
170
  }
156
171
 
157
172
  export function getJitiCliPath(extensionDir: string = EXTENSION_DIR): string {
173
+ const root = resolveAgainstCallerCwd(extensionDir);
158
174
  try {
159
- const jitiPackage = requireFromExtensionDir(extensionDir).resolve("jiti/package.json");
175
+ const jitiPackage = requireFromExtensionDir(root).resolve("jiti/package.json");
160
176
  return join(dirname(jitiPackage), "lib", "jiti-cli.mjs");
161
177
  } catch {
162
- return join(extensionDir, "node_modules", "jiti", "lib", "jiti-cli.mjs");
178
+ return process.platform === "win32"
179
+ ? win32.join(root, "node_modules", "jiti", "lib", "jiti-cli.mjs")
180
+ : join(root, "node_modules", "jiti", "lib", "jiti-cli.mjs");
163
181
  }
164
182
  }
165
183
 
@@ -190,14 +208,6 @@ function getDefaultBrokerCommandParts(
190
208
  return { command: runtimePath, args: [getDefaultBrokerRunnerPath(extensionDir), brokerPath] };
191
209
  }
192
210
 
193
- function quoteWindowsArg(value: string): string {
194
- return `"${value.replace(/"/g, '""')}"`;
195
- }
196
-
197
- export function getWindowsHiddenLauncherPath(intercomDir: string = getIntercomDirPath()): string {
198
- return join(intercomDir, "broker-launch.vbs");
199
- }
200
-
201
211
  function usesDefaultBrokerCommand(brokerCommand: string, brokerArgs: string[]): boolean {
202
212
  return brokerCommand === "npx"
203
213
  && brokerArgs.length === 2
@@ -205,63 +215,70 @@ function usesDefaultBrokerCommand(brokerCommand: string, brokerArgs: string[]):
205
215
  && brokerArgs[1] === "tsx";
206
216
  }
207
217
 
208
- export function getWindowsBrokerCommandLine(
209
- brokerPath: string,
210
- extensionDir: string = EXTENSION_DIR,
211
- nodePath: string = process.execPath,
212
- brokerCommand = "npx",
213
- brokerArgs: string[] = ["--no-install", "tsx"],
214
- runtime: BrokerRuntime = getCurrentBrokerRuntime(),
215
- ): string {
216
- if (usesDefaultBrokerCommand(brokerCommand, brokerArgs)) {
217
- const launch = getDefaultBrokerCommandParts(brokerPath, extensionDir, nodePath, runtime);
218
- return [quoteWindowsArg(launch.command), ...launch.args.map(quoteWindowsArg)].join(" ");
219
- }
218
+ function isWindowsBatchCommand(command: string): boolean {
219
+ return /\.(?:cmd|bat)$/iu.test(command);
220
+ }
220
221
 
221
- return [quoteWindowsArg(brokerCommand), ...brokerArgs.map(quoteWindowsArg), quoteWindowsArg(brokerPath)].join(" ");
222
+ function windowsCmdPath(): string {
223
+ return win32.join(process.env.SystemRoot || process.env.windir || "C:\\Windows", "System32", "cmd.exe");
222
224
  }
223
225
 
224
- /**
225
- * `WshShell.Run` does not hand the launched process the parent's standard handles, so a file
226
- * descriptor passed to `wscript.exe` would only ever capture the launcher. Run the broker under
227
- * `cmd.exe /s /c` instead and append its stderr to the same log the direct path writes.
228
- * `/s` makes cmd strip exactly the outer quote pair and use the remainder verbatim.
229
- *
230
- * Returns the command line unchanged when it contains a `%`. cmd expands `%NAME%` at parse time
231
- * and there is no reliable way to escape a literal percent on a `cmd /c` command line — `^` does
232
- * not cover it, and `%%` is a batch-file escape rather than a command-line one. Wrapping such a
233
- * command would hand the broker different arguments than the user configured, so the redirect is
234
- * dropped instead: launching correctly without a captured log beats launching wrongly with one.
235
- * A `%` reaches here only from a custom `brokerCommand`/`brokerArgs` or an install path that
236
- * contains one, and the direct (non-launcher) Windows path still captures stderr normally.
237
- *
238
- * Nothing may follow the broker in this chain: after the broker's process ends, the resident `cmd.exe` must do no
239
- * file I/O, because tests, `atomic intercom restart` and users remove the intercom directory the moment the broker
240
- * is gone, and a file the chain creates there then fails that removal (the marker an earlier version appended made
241
- * every Windows test that kills a broker and removes its directory fail with ENOTEMPTY). The broker's own start-up
242
- * announcement (`start-announcement.ts`) is how the parent learns that a broker it cannot watch has exited.
243
- */
244
- export function getWindowsStderrRedirectCommandLine(commandLine: string, logPath: string): string {
245
- if (commandLine.includes("%")) return commandLine;
246
- return `cmd.exe /s /c "${commandLine} 2>>${quoteWindowsArg(logPath)}"`;
226
+ function quoteWindowsCmdToken(value: string): string {
227
+ return `"${value.replace(/"/g, '""')}"`;
247
228
  }
248
229
 
249
- export function getWindowsHiddenLauncherScript(commandLine: string): string {
250
- return [
251
- 'Set WshShell = CreateObject("WScript.Shell")',
252
- `WshShell.Run "${commandLine.replace(/"/g, '""')}", 0, False`,
253
- 'Set WshShell = Nothing',
254
- '',
255
- ].join("\r\n");
230
+ function formatWindowsCmdCommandLine(command: string, args: readonly string[]): string {
231
+ // `/s` strips the single outer quote pair and passes the interior verbatim to cmd.exe.
232
+ return `"${[quoteWindowsCmdToken(command), ...args.map(quoteWindowsCmdToken)].join(" ")}"`;
256
233
  }
257
234
 
258
- async function writeWindowsHiddenLauncherAsync(
259
- commandLine: string,
260
- launcherPath: string = getWindowsHiddenLauncherPath(),
261
- ): Promise<string> {
262
- await ensurePrivateDirectoryAsync(dirname(launcherPath));
263
- await writeFile(launcherPath, getWindowsHiddenLauncherScript(commandLine), "utf-8");
264
- return launcherPath;
235
+ function envValueCaseInsensitive(env: NodeJS.ProcessEnv, name: string): string | undefined {
236
+ const key = Object.keys(env)
237
+ .filter((candidate) => candidate.toUpperCase() === name)
238
+ .sort()[0];
239
+ return key === undefined ? undefined : env[key];
240
+ }
241
+
242
+ /**
243
+ * On Windows, resolve a bare custom `brokerCommand` name on `PATH` so `.cmd`/`.bat` shims are recognised and wrapped
244
+ * cleanly with `cmd.exe /d /s /c`, while `.exe`/`.com` commands run directly without a shell. Never searches the
245
+ * working directory unless an explicit absolute `PATH` entry names it.
246
+ */
247
+ async function resolveWindowsCustomCommandAsync(command: string, env: NodeJS.ProcessEnv): Promise<string> {
248
+ if (command === "" || /[\\/:]/u.test(command) || isWindowsBatchCommand(command)) {
249
+ return command;
250
+ }
251
+ const rawPath = envValueCaseInsensitive(env, "PATH") ?? envValueCaseInsensitive(process.env, "PATH") ?? "";
252
+ const rawPathext = envValueCaseInsensitive(env, "PATHEXT") || ".COM;.EXE;.BAT;.CMD";
253
+ const named = rawPathext
254
+ .split(";")
255
+ .map((ext) => ext.trim().toLowerCase())
256
+ .filter((ext) => ext.startsWith("."));
257
+ const extensions = [...named, ...[".com", ".exe"].filter((ext) => !named.includes(ext))];
258
+ const hasExt = win32.extname(command) !== "";
259
+ const names = [...(hasExt ? [command] : []), ...extensions.map((ext) => `${command}${ext}`)];
260
+
261
+ for (const rawEntry of rawPath.split(";")) {
262
+ const entry = rawEntry.trim().replace(/^"(.*)"$/u, "$1");
263
+ if (entry === "" || !win32.isAbsolute(entry)) continue;
264
+ for (const name of names) {
265
+ const candidate = win32.join(entry, name);
266
+ try {
267
+ await access(candidate);
268
+ try {
269
+ const entryStat = await lstat(candidate);
270
+ const isDir = entryStat.isDirectory() || (entryStat.isSymbolicLink() && (await stat(candidate)).isDirectory());
271
+ if (isDir) continue;
272
+ } catch {
273
+ // App execution aliases can be visible to access() while lstat/stat fails; treat as startable.
274
+ }
275
+ return candidate;
276
+ } catch {
277
+ // Not present in this directory.
278
+ }
279
+ }
280
+ }
281
+ return command;
265
282
  }
266
283
 
267
284
  export function getBrokerLaunchSpec(
@@ -270,25 +287,11 @@ export function getBrokerLaunchSpec(
270
287
  brokerArgs: string[],
271
288
  extensionDir: string = EXTENSION_DIR,
272
289
  platform: NodeJS.Platform = process.platform,
273
- intercomDir: string = getIntercomDirPath(),
290
+ _intercomDir: string = getIntercomDirPath(),
274
291
  nodePath: string = process.execPath,
275
292
  runtime: BrokerRuntime = getCurrentBrokerRuntime(),
276
- logPath: string = getBrokerLogPath(),
293
+ _logPath: string = getBrokerLogPath(),
277
294
  ): BrokerLaunchSpec {
278
- if (platform === "win32") {
279
- const launcherPath = getWindowsHiddenLauncherPath(intercomDir);
280
- return {
281
- kind: "windows-launcher",
282
- command: join(process.env.SystemRoot || process.env.windir || "C:\\Windows", "System32", "wscript.exe"),
283
- args: [launcherPath],
284
- launcherPath,
285
- launcherCommandLine: getWindowsStderrRedirectCommandLine(
286
- getWindowsBrokerCommandLine(brokerPath, extensionDir, nodePath, brokerCommand, brokerArgs, runtime),
287
- logPath,
288
- ),
289
- };
290
- }
291
-
292
295
  if (usesDefaultBrokerCommand(brokerCommand, brokerArgs)) {
293
296
  const launch = getDefaultBrokerCommandParts(brokerPath, extensionDir, nodePath, runtime);
294
297
  return {
@@ -298,26 +301,138 @@ export function getBrokerLaunchSpec(
298
301
  };
299
302
  }
300
303
 
304
+ if (platform === "win32" && isWindowsBatchCommand(brokerCommand)) {
305
+ return {
306
+ kind: "direct",
307
+ command: windowsCmdPath(),
308
+ args: ["/d", "/s", "/c", formatWindowsCmdCommandLine(brokerCommand, [...brokerArgs, brokerPath])],
309
+ verbatimArguments: true,
310
+ noWindow: true,
311
+ };
312
+ }
313
+
301
314
  return {
302
315
  kind: "direct",
303
316
  command: brokerCommand,
304
317
  args: [...brokerArgs, brokerPath],
318
+ ...(platform === "win32" ? { noWindow: true as const } : {}),
319
+ };
320
+ }
321
+
322
+ function resolveAgainstCallerCwd(rawPath: string): string {
323
+ if (process.platform === "win32") {
324
+ if (isAbsoluteWindowsPath(rawPath)) return rawPath;
325
+ try {
326
+ return win32.resolve(process.cwd(), rawPath);
327
+ } catch {
328
+ return rawPath;
329
+ }
330
+ }
331
+ return isAbsolute(rawPath) ? rawPath : resolve(rawPath);
332
+ }
333
+
334
+ function brokerSafeCwdOptions(extensionDir: string, commandPath?: string) {
335
+ const resolvedExt = resolveAgainstCallerCwd(extensionDir);
336
+ const installDirs = isBunBinary
337
+ ? [resolvedExt, win32.dirname(resolveAgainstCallerCwd(process.execPath))]
338
+ : [resolvedExt];
339
+ const agentDir = resolveAgainstCallerCwd(getAgentDir());
340
+ const intercomDir = resolveAgainstCallerCwd(getIntercomDirPath());
341
+ return {
342
+ protectedDirs: [intercomDir, agentDir],
343
+ installDirs,
344
+ commandPath,
305
345
  };
306
346
  }
307
347
 
348
+ function resolveBrokerWorkingDirectorySync(extensionDir: string, commandPath?: string): string {
349
+ if (process.platform !== "win32") return "/";
350
+ return (
351
+ resolveSafeWindowsWorkingDirectorySync(brokerSafeCwdOptions(extensionDir, commandPath)) ??
352
+ windowsDriveRoot(resolveAgainstCallerCwd(extensionDir)) ??
353
+ "C:\\"
354
+ );
355
+ }
356
+
357
+ async function resolveBrokerWorkingDirectoryAsync(extensionDir: string, commandPath?: string): Promise<string> {
358
+ if (process.platform !== "win32") return "/";
359
+ return (
360
+ (await resolveSafeWindowsWorkingDirectoryAsync({
361
+ ...brokerSafeCwdOptions(extensionDir, commandPath),
362
+ timeoutMs: 150,
363
+ })) ??
364
+ windowsDriveRoot(resolveAgainstCallerCwd(extensionDir)) ??
365
+ "C:\\"
366
+ );
367
+ }
368
+
369
+ function setEnvValue(env: NodeJS.ProcessEnv, canonicalKey: string, value: string): void {
370
+ if (process.platform !== "win32") {
371
+ env[canonicalKey] = value;
372
+ return;
373
+ }
374
+ const upper = canonicalKey.toUpperCase();
375
+ const matching = Object.keys(env).filter((k) => k.toUpperCase() === upper);
376
+ const targetKey = matching.at(-1) ?? canonicalKey;
377
+ for (const key of matching) {
378
+ if (key !== targetKey) delete env[key];
379
+ }
380
+ env[targetKey] = value;
381
+ }
382
+
383
+ function absolutizeAgentDirEnvInPlace(env: NodeJS.ProcessEnv): void {
384
+ for (const canonicalKey of ["ATOMIC_CODING_AGENT_DIR", "PI_CODING_AGENT_DIR"] as const) {
385
+ const matching =
386
+ process.platform === "win32"
387
+ ? Object.keys(env).filter((k) => k.toUpperCase() === canonicalKey)
388
+ : Object.hasOwn(env, canonicalKey)
389
+ ? [canonicalKey]
390
+ : [];
391
+ if (matching.length === 0) continue;
392
+ const targetKey = matching.at(-1)!;
393
+ const value = env[targetKey];
394
+ for (const key of matching) {
395
+ if (key !== targetKey) delete env[key];
396
+ }
397
+ if (!value || value === "~" || value.startsWith("~/") || (process.platform === "win32" && value.startsWith("~\\"))) {
398
+ continue;
399
+ }
400
+ const needsResolve = process.platform === "win32" ? !isAbsoluteWindowsPath(value) : !isAbsolute(value);
401
+ if (needsResolve) {
402
+ env[targetKey] = resolveAgainstCallerCwd(value);
403
+ }
404
+ }
405
+ }
406
+
308
407
  /**
309
408
  * The broker is detached and outlives this process, so its stderr goes to an already-open file
310
409
  * descriptor rather than a pipe: a long-lived pipe would keep the parent's event loop attached
311
410
  * and break once the parent exits.
312
411
  *
412
+ * Its working directory is always outside the installation directory, the caller's working
413
+ * directory, and the agent directory (`/` on POSIX; a short, verified directory on Windows) so a
414
+ * running broker never holds a directory handle that blocks `npm install -g`, uninstalls, or
415
+ * directory cleanup.
416
+ *
313
417
  * The broker routes through the shared storage this process was launched with (`--storage`,
314
418
  * `--storage-file` or `ATOMIC_STORAGE`), passed as `ATOMIC_STORAGE`; without one it reads settings.
315
419
  * With `announcement` it also gets the file and token it announces its pid with, and asks it to add when it was created
316
420
  * (`start-announcement.ts`).
317
421
  */
422
+ function deleteEnvKeyCaseInsensitive(env: NodeJS.ProcessEnv, canonicalKey: string): void {
423
+ if (process.platform !== "win32") {
424
+ delete env[canonicalKey];
425
+ return;
426
+ }
427
+ const upper = canonicalKey.toUpperCase();
428
+ for (const key of Object.keys(env)) {
429
+ if (key.toUpperCase() === upper) delete env[key];
430
+ }
431
+ }
432
+
318
433
  function buildBrokerSpawnOptions(
319
434
  storage: string | undefined,
320
- extensionDir: string = EXTENSION_DIR,
435
+ cwd: string,
321
436
  stderr: number | "ignore" = "ignore",
322
437
  announcement?: BrokerStartAnnouncement,
323
438
  ): {
@@ -327,21 +442,28 @@ function buildBrokerSpawnOptions(
327
442
  env: NodeJS.ProcessEnv;
328
443
  windowsHide: true;
329
444
  } {
445
+ const env = createChildProcessEnvironment();
446
+ const rawWinPipe =
447
+ process.platform === "win32" ? directBrokerSocketPath("win32", getAgentDirFromEnv(env)) : undefined;
448
+ absolutizeAgentDirEnvInPlace(env);
449
+ const resolvedWinPipe =
450
+ process.platform === "win32" ? directBrokerSocketPath("win32", getAgentDirFromEnv(env)) : undefined;
451
+ deleteEnvKeyCaseInsensitive(env, BROKER_SOCKET_PATH_ENV);
452
+ if (rawWinPipe !== undefined && rawWinPipe !== resolvedWinPipe) {
453
+ setEnvValue(env, BROKER_SOCKET_PATH_ENV, rawWinPipe);
454
+ }
455
+ setEnvValue(env, "NODE_NO_WARNINGS", "1");
456
+ if (storage !== undefined) setEnvValue(env, BROKER_STORAGE_ENV, storage);
457
+ if (announcement !== undefined) {
458
+ setEnvValue(env, BROKER_ANNOUNCE_PATH_ENV, resolveAgainstCallerCwd(announcement.path));
459
+ setEnvValue(env, BROKER_ANNOUNCE_TOKEN_ENV, announcement.token);
460
+ setEnvValue(env, BROKER_ANNOUNCE_START_ENV, "1");
461
+ }
330
462
  return {
331
463
  detached: true,
332
464
  stdio: ["ignore", "ignore", stderr],
333
- cwd: extensionDir,
334
- env: createChildProcessEnvironment({
335
- NODE_NO_WARNINGS: "1",
336
- ...(storage === undefined ? {} : { [BROKER_STORAGE_ENV]: storage }),
337
- ...(announcement === undefined
338
- ? {}
339
- : {
340
- [BROKER_ANNOUNCE_PATH_ENV]: announcement.path,
341
- [BROKER_ANNOUNCE_TOKEN_ENV]: announcement.token,
342
- [BROKER_ANNOUNCE_START_ENV]: "1",
343
- }),
344
- }),
465
+ cwd,
466
+ env,
345
467
  windowsHide: true,
346
468
  };
347
469
  }
@@ -350,6 +472,7 @@ export function getBrokerSpawnOptions(
350
472
  extensionDir: string = EXTENSION_DIR,
351
473
  stderr: number | "ignore" = "ignore",
352
474
  announcement?: BrokerStartAnnouncement,
475
+ commandPath?: string,
353
476
  ): {
354
477
  detached: true;
355
478
  stdio: ["ignore", "ignore", number | "ignore"];
@@ -357,13 +480,19 @@ export function getBrokerSpawnOptions(
357
480
  env: NodeJS.ProcessEnv;
358
481
  windowsHide: true;
359
482
  } {
360
- return buildBrokerSpawnOptions(processSharedStorageSelection(), extensionDir, stderr, announcement);
483
+ return buildBrokerSpawnOptions(
484
+ processSharedStorageSelection(),
485
+ resolveBrokerWorkingDirectorySync(extensionDir, commandPath),
486
+ stderr,
487
+ announcement,
488
+ );
361
489
  }
362
490
 
363
491
  export async function getBrokerSpawnOptionsAsync(
364
492
  extensionDir: string = EXTENSION_DIR,
365
493
  stderr: number | "ignore" = "ignore",
366
494
  announcement?: BrokerStartAnnouncement,
495
+ commandPath?: string,
367
496
  ): Promise<{
368
497
  detached: true;
369
498
  stdio: ["ignore", "ignore", number | "ignore"];
@@ -371,7 +500,11 @@ export async function getBrokerSpawnOptionsAsync(
371
500
  env: NodeJS.ProcessEnv;
372
501
  windowsHide: true;
373
502
  }> {
374
- return buildBrokerSpawnOptions(await processSharedStorageSelectionAsync(), extensionDir, stderr, announcement);
503
+ const [storage, cwd] = await Promise.all([
504
+ processSharedStorageSelectionAsync(),
505
+ resolveBrokerWorkingDirectoryAsync(extensionDir, commandPath),
506
+ ]);
507
+ return buildBrokerSpawnOptions(storage, cwd, stderr, announcement);
375
508
  }
376
509
 
377
510
  /**
@@ -553,6 +686,580 @@ async function waitForBrokerOrTakeOver(
553
686
  throw await brokerStartTimeoutError(readyTimeoutMs);
554
687
  }
555
688
 
689
+ interface NativeDetachedProcess {
690
+ readonly pid: number;
691
+ readonly creationTime?: string | null;
692
+ kill(signal: number, group: boolean): boolean;
693
+ unref(): void;
694
+ release(): void;
695
+ }
696
+
697
+ interface NativeHostProcessEvent {
698
+ readonly kind: string;
699
+ readonly code?: number;
700
+ }
701
+
702
+ interface NativeDetachedStartOptions {
703
+ readonly file: string;
704
+ readonly args: string[];
705
+ readonly cwd?: string;
706
+ readonly env: Record<string, string>;
707
+ readonly pipeStdin: false;
708
+ readonly pipeStdout: false;
709
+ readonly pipeStderr: false;
710
+ readonly detached: true;
711
+ readonly stderrLogPath?: string;
712
+ readonly verbatimArguments?: boolean;
713
+ readonly noWindow?: boolean;
714
+ readonly watchPid?: number;
715
+ readonly watchCreationTime?: string;
716
+ }
717
+
718
+ type NativeStartHostProcess = (
719
+ options: NativeDetachedStartOptions,
720
+ onEvent: (event: NativeHostProcessEvent) => void,
721
+ ) => NativeDetachedProcess;
722
+
723
+ interface NativeBrokerSpawnBindings {
724
+ readonly startHostProcess: NativeStartHostProcess | null;
725
+ readonly modulePath: string | undefined;
726
+ }
727
+
728
+ let nativeBrokerSpawnBindings: NativeBrokerSpawnBindings | undefined;
729
+
730
+ function loadNativeBrokerSpawnBindings(): NativeBrokerSpawnBindings {
731
+ if (process.platform !== "win32") {
732
+ return { startHostProcess: null, modulePath: undefined };
733
+ }
734
+ if (nativeBrokerSpawnBindings === undefined) {
735
+ let startHostProcess: NativeStartHostProcess | null = null;
736
+ let modulePath: string | undefined;
737
+ try {
738
+ const req = createRequire(import.meta.url);
739
+ try {
740
+ modulePath = req.resolve("@bastani/atomic-natives");
741
+ } catch {
742
+ modulePath = undefined;
743
+ }
744
+ const binding = req(modulePath ?? "@bastani/atomic-natives") as {
745
+ readonly startHostProcess?: NativeStartHostProcess;
746
+ };
747
+ startHostProcess = typeof binding.startHostProcess === "function" ? binding.startHostProcess : null;
748
+ } catch {
749
+ startHostProcess = null;
750
+ }
751
+ nativeBrokerSpawnBindings = { startHostProcess, modulePath };
752
+ }
753
+ return nativeBrokerSpawnBindings;
754
+ }
755
+
756
+ function stringOnlyEnv(env: NodeJS.ProcessEnv): Record<string, string> {
757
+ const result: Record<string, string> = {};
758
+ for (const [key, value] of Object.entries(env)) {
759
+ if (value !== undefined) result[key] = value;
760
+ }
761
+ return result;
762
+ }
763
+
764
+ /**
765
+ * Minimal relay script run in a short-lived detached child on Windows so the Intercom broker is orphaned outside the
766
+ * launching engine's process tree (its `InheritedFromUniqueProcessId` is the exited relay). Without this, escalating a
767
+ * hung engine via `holdProcessDescendants` or `taskkill /T` would terminate the shared Intercom broker serving other
768
+ * sessions. The relay reads one JSON request on stdin, starts the broker (breaking away from the parent job when
769
+ * allowed), writes `{ ok, pid, creationTime }` on stdout while holding the broker's handle so the parent can attach a
770
+ * verified watch handle without PID-reuse races, and exits immediately once stdin closes.
771
+ */
772
+ const WINDOWS_BROKER_RELAY_SCRIPT = [
773
+ 'const fs = require("node:fs");',
774
+ 'const cp = require("node:child_process");',
775
+ 'let buf = "", launched = false, held = null;',
776
+ 'function done() { try { held?.release?.(); } catch {} process.exit(0); }',
777
+ 'function reply(o) { process.stdout.write(JSON.stringify(o) + "\\n"); }',
778
+ 'process.stdin.setEncoding("utf8");',
779
+ 'process.stdin.on("data", (chunk) => {',
780
+ ' if (launched) return;',
781
+ ' buf += chunk;',
782
+ ' const nl = buf.indexOf("\\n");',
783
+ ' if (nl === -1) return;',
784
+ ' launched = true;',
785
+ ' try {',
786
+ ' const req = JSON.parse(buf.slice(0, nl));',
787
+ ' let native = null;',
788
+ ' if (req.nativePath) { try { native = require(req.nativePath); } catch {} }',
789
+ ' if (typeof native?.startHostProcess === "function") {',
790
+ ' try {',
791
+ ' const p = native.startHostProcess({ file: req.file, args: req.args, cwd: req.cwd, env: req.env, pipeStdin: false, pipeStdout: false, pipeStderr: false, detached: true, stderrLogPath: req.stderrLogPath, ...(req.verbatimArguments ? { verbatimArguments: true } : {}), ...(req.noWindow ? { noWindow: true } : {}) }, () => {});',
792
+ ' p.unref();',
793
+ ' held = p;',
794
+ ' reply({ ok: true, pid: p.pid, creationTime: p.creationTime ?? null });',
795
+ ' return;',
796
+ ' } catch (e) {',
797
+ ' if (e?.code !== "ENOSYS" && e?.code !== "ENOTSUP") throw e;',
798
+ ' }',
799
+ ' }',
800
+ ' const fd = fs.openSync(req.stderrLogPath, "a");',
801
+ ' try {',
802
+ ' const c = cp.spawn(req.file, req.args, { detached: true, windowsHide: true, cwd: req.cwd, env: req.env, stdio: ["ignore", "ignore", fd], ...(req.verbatimArguments ? { windowsVerbatimArguments: true } : {}) });',
803
+ ' c.once("spawn", () => {',
804
+ ' c.unref();',
805
+ ' let started = null;',
806
+ ' if (c.exitCode === null && c.signalCode === null && c.pid && typeof native?.processCreationTime === "function") { try { started = native.processCreationTime(c.pid) ?? null; } catch {} }',
807
+ ' reply({ ok: true, pid: c.pid ?? null, creationTime: started });',
808
+ ' });',
809
+ ' c.once("error", (e) => reply({ ok: false, code: e?.code ?? "UNKNOWN", message: e?.message ?? String(e) }));',
810
+ ' } finally { fs.closeSync(fd); }',
811
+ ' } catch (e) {',
812
+ ' reply({ ok: false, code: e?.code ?? "UNKNOWN", message: e?.message ?? String(e) });',
813
+ ' }',
814
+ '});',
815
+ 'process.stdin.on("end", done);',
816
+ 'setTimeout(done, 5000).unref();',
817
+ ].join("\n");
818
+
819
+ const WINDOWS_RELAY_HANDSHAKE_TIMEOUT_MS = 10_000;
820
+ const WINDOWS_RELAY_EXIT_TIMEOUT_MS = 2_000;
821
+
822
+ interface WindowsRelaySpec {
823
+ readonly command: string;
824
+ readonly args: string[];
825
+ }
826
+
827
+ function getWindowsRelaySpec(
828
+ runtime: BrokerRuntime = getCurrentBrokerRuntime(),
829
+ runtimePath: string = process.execPath,
830
+ ): WindowsRelaySpec | undefined {
831
+ if (runtime === "bun-binary") {
832
+ const supported = (globalThis as Record<symbol, unknown>)[INTERNAL_INTERCOM_BROKER_RELAY_CAPABILITY] === true;
833
+ return supported ? { command: runtimePath, args: [INTERNAL_INTERCOM_BROKER_RELAY_ARG] } : undefined;
834
+ }
835
+ if (runtime === "bun-source") {
836
+ return { command: runtimePath, args: ["-e", WINDOWS_BROKER_RELAY_SCRIPT] };
837
+ }
838
+ return { command: runtimePath, args: ["--no-warnings", "-e", WINDOWS_BROKER_RELAY_SCRIPT] };
839
+ }
840
+
841
+ function cleanRelayEnvironment(): NodeJS.ProcessEnv {
842
+ const env: NodeJS.ProcessEnv = {};
843
+ for (const [key, value] of Object.entries(process.env)) {
844
+ if (value === undefined) continue;
845
+ // Do not run user/test preloads or debuggers inside the short-lived relay; the broker itself receives the full env.
846
+ if (key.toUpperCase() === "NODE_OPTIONS") continue;
847
+ env[key] = value;
848
+ }
849
+ return env;
850
+ }
851
+
852
+ interface SpawnedBrokerChild {
853
+ readonly pid: number | undefined;
854
+ /** Kernel creation time read while a live process handle was held (Windows), when available. */
855
+ readonly started: string | undefined;
856
+ /** True while this process holds a live OS handle to the broker preventing Windows PID reuse. */
857
+ readonly holdsProcessHandle: boolean;
858
+ readonly exitCode: number | null;
859
+ readonly signalCode: NodeJS.Signals | null;
860
+ /** Non-native Windows fallback only: poll liveness of the orphaned broker via waitForBroker. */
861
+ readonly polledIdentity?: () => AnnouncedBroker | undefined;
862
+ onceError(listener: (error: Error) => void): void;
863
+ offError(listener: (error: Error) => void): void;
864
+ onceExit(listener: (code: number | null, signal: NodeJS.Signals | null) => void): void;
865
+ offExit(listener: (code: number | null, signal: NodeJS.Signals | null) => void): void;
866
+ killHandle(): void;
867
+ release(): void;
868
+ }
869
+
870
+ function wrapNativeProcessHandle(
871
+ proc: NativeDetachedProcess,
872
+ started: string | undefined,
873
+ readExitCode: () => number | null,
874
+ setExitListener: (listener: ((code: number | null, signal: NodeJS.Signals | null) => void) | undefined) => void,
875
+ clearExitListener: (listener: (code: number | null, signal: NodeJS.Signals | null) => void) => void,
876
+ ): SpawnedBrokerChild {
877
+ return {
878
+ pid: proc.pid,
879
+ started,
880
+ holdsProcessHandle: true,
881
+ get exitCode() {
882
+ return readExitCode();
883
+ },
884
+ get signalCode() {
885
+ return null;
886
+ },
887
+ onceError() {
888
+ // Native start/watch reports launch errors synchronously via throw.
889
+ },
890
+ offError() {},
891
+ onceExit(listener) {
892
+ const code = readExitCode();
893
+ if (code !== null) {
894
+ queueMicrotask(() => listener(code, null));
895
+ return;
896
+ }
897
+ setExitListener(listener);
898
+ },
899
+ offExit(listener) {
900
+ clearExitListener(listener);
901
+ },
902
+ killHandle() {
903
+ try {
904
+ proc.kill(9, false);
905
+ } catch {}
906
+ },
907
+ release() {
908
+ setExitListener(undefined);
909
+ try {
910
+ proc.release();
911
+ } catch {}
912
+ },
913
+ };
914
+ }
915
+
916
+ function wrapNativeDetachedProcess(
917
+ startNative: NativeStartHostProcess,
918
+ launch: BrokerLaunchSpec,
919
+ spawnOptions: ReturnType<typeof buildBrokerSpawnOptions>,
920
+ logPath: string,
921
+ ): SpawnedBrokerChild | undefined {
922
+ let exitCode: number | null = null;
923
+ let exitListener: ((code: number | null, signal: NodeJS.Signals | null) => void) | undefined;
924
+ let proc: NativeDetachedProcess;
925
+ try {
926
+ proc = startNative(
927
+ {
928
+ file: launch.command,
929
+ args: launch.args,
930
+ cwd: spawnOptions.cwd,
931
+ env: stringOnlyEnv(spawnOptions.env),
932
+ pipeStdin: false,
933
+ pipeStdout: false,
934
+ pipeStderr: false,
935
+ detached: true,
936
+ stderrLogPath: logPath,
937
+ ...(launch.verbatimArguments ? { verbatimArguments: true } : {}),
938
+ ...(launch.noWindow ? { noWindow: true } : {}),
939
+ },
940
+ (event) => {
941
+ if (event.kind !== "exit") return;
942
+ exitCode = event.code ?? -1;
943
+ const listener = exitListener;
944
+ exitListener = undefined;
945
+ listener?.(exitCode, null);
946
+ },
947
+ );
948
+ } catch (error) {
949
+ const code = (error as NodeJS.ErrnoException).code;
950
+ // Older native addon before Windows detached support: fall back to direct child_process.spawn.
951
+ if (code === "ENOSYS" || code === "ENOTSUP") return undefined;
952
+ throw error;
953
+ }
954
+ proc.unref();
955
+ const started = proc.creationTime ?? nativeProcessCreationTime(proc.pid);
956
+ return wrapNativeProcessHandle(
957
+ proc,
958
+ started,
959
+ () => exitCode,
960
+ (listener) => {
961
+ exitListener = listener;
962
+ },
963
+ (listener) => {
964
+ if (exitListener === listener) exitListener = undefined;
965
+ },
966
+ );
967
+ }
968
+
969
+ function watchOrphanedWindowsProcess(
970
+ startNative: NativeStartHostProcess,
971
+ pid: number,
972
+ creationTime: string,
973
+ ): SpawnedBrokerChild | undefined {
974
+ let exitCode: number | null = null;
975
+ let exitListener: ((code: number | null, signal: NodeJS.Signals | null) => void) | undefined;
976
+ let proc: NativeDetachedProcess;
977
+ try {
978
+ proc = startNative(
979
+ {
980
+ file: "",
981
+ args: [],
982
+ env: {},
983
+ pipeStdin: false,
984
+ pipeStdout: false,
985
+ pipeStderr: false,
986
+ detached: true,
987
+ watchPid: pid,
988
+ watchCreationTime: creationTime,
989
+ },
990
+ (event) => {
991
+ if (event.kind !== "exit") return;
992
+ exitCode = event.code ?? -1;
993
+ const listener = exitListener;
994
+ exitListener = undefined;
995
+ listener?.(exitCode, null);
996
+ },
997
+ );
998
+ } catch {
999
+ return undefined;
1000
+ }
1001
+ proc.unref();
1002
+ return wrapNativeProcessHandle(
1003
+ proc,
1004
+ creationTime,
1005
+ () => exitCode,
1006
+ (listener) => {
1007
+ exitListener = listener;
1008
+ },
1009
+ (listener) => {
1010
+ if (exitListener === listener) exitListener = undefined;
1011
+ },
1012
+ );
1013
+ }
1014
+
1015
+ interface RelayResponse {
1016
+ readonly ok: boolean;
1017
+ readonly pid?: number | null;
1018
+ readonly creationTime?: string | null;
1019
+ readonly code?: string;
1020
+ readonly message?: string;
1021
+ }
1022
+
1023
+ /**
1024
+ * Start the Windows broker through a short-lived detached relay that exits immediately after handing the broker's
1025
+ * `(pid, creationTime)` back while holding its handle. Once the relay exits, the broker's `InheritedFromUniqueProcessId`
1026
+ * names the dead relay, so a hung-engine tree kill (`holdProcessDescendants` or `taskkill /T`) never ends the shared
1027
+ * broker while still ending every other descendant of the engine.
1028
+ */
1029
+ async function spawnOrphanedWindowsBrokerAsync(
1030
+ launch: BrokerLaunchSpec,
1031
+ spawnOptions: ReturnType<typeof buildBrokerSpawnOptions>,
1032
+ logPath: string,
1033
+ bindings: NativeBrokerSpawnBindings,
1034
+ ): Promise<SpawnedBrokerChild | undefined> {
1035
+ const relaySpec = getWindowsRelaySpec();
1036
+ if (relaySpec === undefined) return undefined;
1037
+
1038
+ let relay: ReturnType<typeof spawn>;
1039
+ try {
1040
+ relay = spawn(relaySpec.command, relaySpec.args, {
1041
+ detached: true,
1042
+ windowsHide: true,
1043
+ cwd: spawnOptions.cwd,
1044
+ env: cleanRelayEnvironment(),
1045
+ stdio: ["pipe", "pipe", "ignore"],
1046
+ });
1047
+ } catch {
1048
+ return undefined;
1049
+ }
1050
+ relay.stdin?.on("error", () => {});
1051
+ relay.stdout?.on("error", () => {});
1052
+
1053
+ const relayExited = new Promise<void>((resolve) => {
1054
+ if (relay.exitCode !== null || relay.signalCode !== null) {
1055
+ resolve();
1056
+ return;
1057
+ }
1058
+ relay.once("exit", () => resolve());
1059
+ relay.once("error", () => resolve());
1060
+ });
1061
+
1062
+ const endRelayAndWait = async (): Promise<void> => {
1063
+ try {
1064
+ relay.stdin?.end();
1065
+ } catch {}
1066
+ let timer: ReturnType<typeof setTimeout> | undefined;
1067
+ const exitedInTime = await Promise.race([
1068
+ relayExited.then(() => true),
1069
+ new Promise<false>((resolve) => {
1070
+ timer = setTimeout(() => resolve(false), WINDOWS_RELAY_EXIT_TIMEOUT_MS);
1071
+ timer.unref();
1072
+ }),
1073
+ ]);
1074
+ if (timer !== undefined) clearTimeout(timer);
1075
+ if (!exitedInTime) {
1076
+ try {
1077
+ relay.kill("SIGKILL");
1078
+ } catch {}
1079
+ await Promise.race([relayExited, sleep(500)]);
1080
+ }
1081
+ };
1082
+
1083
+ const response = await new Promise<RelayResponse | undefined>((resolve) => {
1084
+ let stdout = "";
1085
+ let settled = false;
1086
+ const finish = (value: RelayResponse | undefined) => {
1087
+ if (settled) return;
1088
+ settled = true;
1089
+ clearTimeout(timer);
1090
+ relay.stdout?.off("data", onData);
1091
+ relay.off("error", onError);
1092
+ relay.off("exit", onExit);
1093
+ resolve(value);
1094
+ };
1095
+ const onData = (chunk: Buffer | string) => {
1096
+ stdout += typeof chunk === "string" ? chunk : chunk.toString("utf8");
1097
+ const nl = stdout.indexOf("\n");
1098
+ if (nl === -1) return;
1099
+ try {
1100
+ finish(JSON.parse(stdout.slice(0, nl)) as RelayResponse);
1101
+ } catch {
1102
+ finish(undefined);
1103
+ }
1104
+ };
1105
+ const onError = () => finish(undefined);
1106
+ const onExit = () => finish(undefined);
1107
+ const timer = setTimeout(() => finish(undefined), WINDOWS_RELAY_HANDSHAKE_TIMEOUT_MS);
1108
+ timer.unref();
1109
+
1110
+ relay.stdout?.on("data", onData);
1111
+ relay.once("error", onError);
1112
+ relay.once("exit", onExit);
1113
+
1114
+ try {
1115
+ const payload = JSON.stringify({
1116
+ file: launch.command,
1117
+ args: launch.args,
1118
+ cwd: spawnOptions.cwd,
1119
+ env: stringOnlyEnv(spawnOptions.env),
1120
+ stderrLogPath: logPath,
1121
+ ...(launch.verbatimArguments ? { verbatimArguments: true } : {}),
1122
+ ...(launch.noWindow ? { noWindow: true } : {}),
1123
+ ...(bindings.modulePath ? { nativePath: bindings.modulePath } : {}),
1124
+ });
1125
+ relay.stdin?.write(`${payload}\n`);
1126
+ } catch {
1127
+ finish(undefined);
1128
+ }
1129
+ });
1130
+
1131
+ if (response === undefined) {
1132
+ await endRelayAndWait();
1133
+ return undefined;
1134
+ }
1135
+
1136
+ if (!response.ok) {
1137
+ await endRelayAndWait();
1138
+ const error = new Error(response.message ?? "Failed to spawn intercom broker") as NodeJS.ErrnoException;
1139
+ if (response.code) error.code = response.code;
1140
+ throw error;
1141
+ }
1142
+
1143
+ const pid = typeof response.pid === "number" && Number.isInteger(response.pid) && response.pid > 0 ? response.pid : undefined;
1144
+ const creationTime = typeof response.creationTime === "string" && response.creationTime.length > 0 ? response.creationTime : undefined;
1145
+
1146
+ // Open a verified watch handle while the relay still holds the broker's handle, so PID reuse is impossible and even
1147
+ // an instant startup crash delivers its exact exit code.
1148
+ let watched: SpawnedBrokerChild | undefined;
1149
+ if (pid !== undefined && creationTime !== undefined && bindings.startHostProcess !== null) {
1150
+ watched = watchOrphanedWindowsProcess(bindings.startHostProcess, pid, creationTime);
1151
+ }
1152
+
1153
+ // Signal the relay to drop its handle and wait until it has exited, guaranteeing the broker is orphaned from this
1154
+ // process's descendant tree before spawn returns.
1155
+ await endRelayAndWait();
1156
+
1157
+ if (watched !== undefined) return watched;
1158
+
1159
+ // Fallback when watchPid is unavailable (older native addon or no addon): poll liveness via waitForBroker.
1160
+ // #6133: the relay has already exited so no OS handle prevents PID reuse here; keep ONLY a creationTime captured
1161
+ // while the relay held the handle, and never read a creation time lazily for an unheld bare PID.
1162
+ const started = creationTime;
1163
+ const polledIdentity: (() => AnnouncedBroker | undefined) | undefined =
1164
+ pid === undefined ? undefined : () => (started === undefined ? { pid } : { pid, started });
1165
+ return {
1166
+ pid,
1167
+ started,
1168
+ holdsProcessHandle: false,
1169
+ get exitCode() {
1170
+ return pid !== undefined && !isProcessAlive(pid) ? -1 : null;
1171
+ },
1172
+ get signalCode() {
1173
+ return null;
1174
+ },
1175
+ polledIdentity,
1176
+ onceError() {},
1177
+ offError() {},
1178
+ onceExit() {},
1179
+ offExit() {},
1180
+ killHandle() {},
1181
+ release() {},
1182
+ };
1183
+ }
1184
+
1185
+ function wrapNodeChildProcess(
1186
+ child: ReturnType<typeof spawn>,
1187
+ started: string | undefined,
1188
+ ): SpawnedBrokerChild {
1189
+ let bufferedError: Error | undefined;
1190
+ let bufferedExit: { code: number | null; signal: NodeJS.Signals | null } | undefined;
1191
+ let errorListener: ((error: Error) => void) | undefined;
1192
+ let exitListener: ((code: number | null, signal: NodeJS.Signals | null) => void) | undefined;
1193
+
1194
+ const onError = (error: Error) => {
1195
+ if (errorListener !== undefined) {
1196
+ const listener = errorListener;
1197
+ errorListener = undefined;
1198
+ listener(error);
1199
+ } else {
1200
+ bufferedError = error;
1201
+ }
1202
+ };
1203
+ const onExit = (code: number | null, signal: NodeJS.Signals | null) => {
1204
+ if (exitListener !== undefined) {
1205
+ const listener = exitListener;
1206
+ exitListener = undefined;
1207
+ listener(code, signal);
1208
+ } else {
1209
+ bufferedExit = { code, signal };
1210
+ }
1211
+ };
1212
+ child.once("error", onError);
1213
+ child.once("exit", onExit);
1214
+
1215
+ return {
1216
+ pid: child.pid,
1217
+ started,
1218
+ holdsProcessHandle: true,
1219
+ get exitCode() {
1220
+ return child.exitCode ?? bufferedExit?.code ?? null;
1221
+ },
1222
+ get signalCode() {
1223
+ return child.signalCode ?? bufferedExit?.signal ?? null;
1224
+ },
1225
+ onceError(listener) {
1226
+ if (bufferedError !== undefined) {
1227
+ const error = bufferedError;
1228
+ bufferedError = undefined;
1229
+ queueMicrotask(() => listener(error));
1230
+ return;
1231
+ }
1232
+ errorListener = listener;
1233
+ },
1234
+ offError(listener) {
1235
+ if (errorListener === listener) errorListener = undefined;
1236
+ },
1237
+ onceExit(listener) {
1238
+ if (bufferedExit !== undefined) {
1239
+ const exit = bufferedExit;
1240
+ bufferedExit = undefined;
1241
+ queueMicrotask(() => listener(exit.code, exit.signal));
1242
+ return;
1243
+ }
1244
+ exitListener = listener;
1245
+ },
1246
+ offExit(listener) {
1247
+ if (exitListener === listener) exitListener = undefined;
1248
+ },
1249
+ killHandle() {
1250
+ try {
1251
+ child.kill("SIGKILL");
1252
+ } catch {}
1253
+ },
1254
+ release() {
1255
+ errorListener = undefined;
1256
+ exitListener = undefined;
1257
+ child.off("error", onError);
1258
+ child.off("exit", onExit);
1259
+ },
1260
+ };
1261
+ }
1262
+
556
1263
  /**
557
1264
  * Start a broker while holding the spawn lock `lockOwner` wrote, and release it, unless a broker still starting takes
558
1265
  * it over. `recheck` returns at once when a broker answers by now. An aborted `signal` cancels the start before the
@@ -576,51 +1283,84 @@ async function spawnBrokerHoldingLock(
576
1283
  }
577
1284
  cancelSignal?.throwIfAborted();
578
1285
 
579
- const brokerPath = await resolveBrokerEntrypointAsync(extensionDir);
580
- const launch = getBrokerLaunchSpec(brokerPath, brokerCommand, brokerArgs, extensionDir);
581
- // The Windows launcher hides the broker's pid and exit, so there the broker announces its pid, which this watches.
582
- // Elsewhere the child is the broker and its exit event says how it ended.
583
- const announcement: BrokerStartAnnouncement | undefined =
584
- launch.kind === "windows-launcher" ? { path: getBrokerStartAnnouncementPath(), token: randomUUID() } : undefined;
585
- if (announcement !== undefined) {
586
- try {
587
- await unlink(announcement.path);
588
- } catch {
589
- // None left by an earlier broker, or not removable: its token is not this spawn's, so it is ignored.
590
- }
591
- }
592
- if (launch.kind === "windows-launcher") {
593
- await writeWindowsHiddenLauncherAsync(launch.launcherCommandLine, launch.launcherPath);
594
- }
595
- // Reset before spawning either way: the Windows launcher appends to this same path.
1286
+ const resolvedExtensionDir = resolveAgainstCallerCwd(extensionDir);
1287
+ const brokerPath = await resolveBrokerEntrypointAsync(resolvedExtensionDir);
1288
+ const isCustomPath =
1289
+ !usesDefaultBrokerCommand(brokerCommand, brokerArgs) &&
1290
+ (/[\\/]/u.test(brokerCommand) || (process.platform === "win32" && /^[A-Za-z]:/u.test(brokerCommand)));
1291
+ const normalizedCustomCommand =
1292
+ isCustomPath && (process.platform === "win32" ? !isAbsoluteWindowsPath(brokerCommand) : !isAbsolute(brokerCommand))
1293
+ ? resolveAgainstCallerCwd(brokerCommand)
1294
+ : brokerCommand;
1295
+ const initialCommandPath = usesDefaultBrokerCommand(brokerCommand, brokerArgs)
1296
+ ? process.execPath
1297
+ : normalizedCustomCommand;
1298
+ const baseSpawnOptions = await getBrokerSpawnOptionsAsync(
1299
+ resolvedExtensionDir,
1300
+ "ignore",
1301
+ undefined,
1302
+ initialCommandPath,
1303
+ );
1304
+ const effectiveCommand =
1305
+ process.platform === "win32" && !usesDefaultBrokerCommand(brokerCommand, brokerArgs)
1306
+ ? await resolveWindowsCustomCommandAsync(normalizedCustomCommand, baseSpawnOptions.env)
1307
+ : normalizedCustomCommand;
1308
+ const launch = getBrokerLaunchSpec(brokerPath, effectiveCommand, brokerArgs, resolvedExtensionDir);
1309
+ // Reset before spawning: on Windows an older broker launcher's `cmd.exe` redirect may still hold broker.log
1310
+ // briefly after exiting, so wait up to BROKER_LOG_RELEASE_WAIT_MS before concluding a broker is still starting.
596
1311
  if (!(await resetBrokerLogOnceReleased())) {
597
1312
  await waitForBroker(readyTimeoutMs, undefined, cancelSignal);
598
1313
  return;
599
1314
  }
600
1315
  // The last point before the broker exists; from here it is waited for, never abandoned while it starts.
601
1316
  cancelSignal?.throwIfAborted();
602
- // The Windows launcher redirects the broker's own stderr, so only the direct spawn
603
- // needs the descriptor. Node duplicates it during spawn, so the parent copy is closed
604
- // immediately afterwards rather than being held open for the broker's lifetime.
605
- const logHandle = launch.kind === "direct" ? await open(getBrokerLogPath(), "a") : undefined;
606
- let child: ReturnType<typeof spawn>;
607
- try {
608
- const spawnOptions = await getBrokerSpawnOptionsAsync(extensionDir, logHandle?.fd ?? "ignore", announcement);
609
- child = spawn(
610
- launch.command,
611
- launch.args,
612
- spawnOptions,
613
- );
614
- } catch (error) {
615
- await logHandle?.close();
616
- throw error;
1317
+
1318
+ const logPath = resolveAgainstCallerCwd(getBrokerLogPath());
1319
+ let logHandle: FileHandle | undefined;
1320
+ let child: SpawnedBrokerChild | undefined;
1321
+ if (process.platform === "win32") {
1322
+ const bindings = loadNativeBrokerSpawnBindings();
1323
+ try {
1324
+ child = await spawnOrphanedWindowsBrokerAsync(launch, baseSpawnOptions, logPath, bindings);
1325
+ if (child === undefined && bindings.startHostProcess !== null) {
1326
+ child = wrapNativeDetachedProcess(bindings.startHostProcess, launch, baseSpawnOptions, logPath);
1327
+ }
1328
+ } catch (error) {
1329
+ const cause = toError(error);
1330
+ const log = await describeBrokerLogAsync();
1331
+ throw new Error(`Failed to spawn intercom broker: ${cause.message}\n${log}`, { cause });
1332
+ }
1333
+ }
1334
+ if (child === undefined) {
1335
+ // Direct child_process.spawn path (all POSIX platforms, and Windows fallback if both relay and native spawn are unavailable).
1336
+ // Node duplicates the append descriptor during spawn, so the parent copy is closed immediately afterwards rather
1337
+ // than being held open for the broker's lifetime.
1338
+ logHandle = await open(logPath, "a");
1339
+ try {
1340
+ const spawnOptions = {
1341
+ ...baseSpawnOptions,
1342
+ stdio: ["ignore", "ignore", logHandle.fd] as ["ignore", "ignore", number],
1343
+ ...(launch.verbatimArguments ? { windowsVerbatimArguments: true } : {}),
1344
+ };
1345
+ const rawChild = spawn(launch.command, launch.args, spawnOptions);
1346
+ rawChild.unref();
1347
+ const childStarted =
1348
+ process.platform === "win32" && rawChild.pid !== undefined
1349
+ ? nativeProcessCreationTime(rawChild.pid)
1350
+ : undefined;
1351
+ child = wrapNodeChildProcess(rawChild, childStarted);
1352
+ } catch (error) {
1353
+ await logHandle.close();
1354
+ throw error;
1355
+ }
617
1356
  }
618
- child.unref();
619
1357
 
1358
+ const spawned = child;
620
1359
  const started = new Promise<void>((resolve, reject) => {
621
- const cleanup = () => {
622
- child.off("error", onError);
623
- child.off("exit", onExit);
1360
+ const cleanup = (releaseHandle = true) => {
1361
+ spawned.offError(onError);
1362
+ spawned.offExit(onExit);
1363
+ if (releaseHandle) spawned.release();
624
1364
  };
625
1365
 
626
1366
  const onError = (error: Error) => {
@@ -631,9 +1371,6 @@ async function spawnBrokerHoldingLock(
631
1371
  };
632
1372
 
633
1373
  const onExit = (code: number | null, exitSignal: NodeJS.Signals | null) => {
634
- if (launch.kind === "windows-launcher" && code === 0 && exitSignal === null) {
635
- return;
636
- }
637
1374
  cleanup();
638
1375
  if (exitSignal) {
639
1376
  void describeBrokerLogAsync().then((log) =>
@@ -654,54 +1391,62 @@ async function spawnBrokerHoldingLock(
654
1391
  rejectExitedBeforeStartup();
655
1392
  };
656
1393
 
657
- child.once("error", onError);
658
- child.once("exit", onExit);
1394
+ spawned.onceError(onError);
1395
+ spawned.onceExit(onExit);
659
1396
  // A disposed session stops waiting at once; the broker it launched is then stopped below, so the call still never
660
1397
  // returns while that broker is writing its start-up files.
661
- waitForBroker(
662
- readyTimeoutMs,
663
- announcement === undefined ? undefined : () => readBrokerStartAnnouncementAsync(announcement),
664
- cancelSignal,
665
- ).then(() => {
1398
+ waitForBroker(readyTimeoutMs, spawned.polledIdentity, cancelSignal).then(() => {
666
1399
  cleanup();
667
1400
  resolve();
668
1401
  }, async (error) => {
669
- cleanup();
670
- const starting = launch.kind === "direct" && child.exitCode === null && child.signalCode === null;
671
- // #4727: the session that launched this broker is gone and the broker did not start in time; it is stopped
672
- // before this call returns, so it never writes into an agent directory its host may already be removing. Behind
673
- // the Windows launcher the broker is found by the pid it announced; one that never announced cannot be found,
674
- // and one that did not announce when it was created cannot be told apart from a later process given its pid
675
- // (#6133), so neither is stopped.
676
- let abandoned: StartingBroker | undefined;
677
- if (signal?.aborted) {
678
- if (launch.kind === "direct") {
679
- if (starting && child.pid !== undefined) abandoned = { kind: "group", pid: child.pid };
680
- } else if (announcement !== undefined) {
681
- const announced = await readBrokerStartAnnouncementAsync(announcement);
682
- if (announced?.started !== undefined) {
683
- abandoned = { kind: "announced", pid: announced.pid, started: announced.started };
1402
+ // Keep the OS process handle open while stopping or handing off the spawn lock so its PID cannot be recycled.
1403
+ cleanup(false);
1404
+ try {
1405
+ const starting = spawned.exitCode === null && spawned.signalCode === null;
1406
+ // #4727 / #6133: the session that launched this broker is gone and the broker did not start in time; stop it
1407
+ // (and every descendant it started) before this call returns, never by an unverified bare PID on Windows.
1408
+ if (signal?.aborted && starting && spawned.pid !== undefined) {
1409
+ let abandoned: StartingBroker | undefined;
1410
+ if (process.platform === "win32") {
1411
+ // Only query creation time lazily while THIS process still holds the child's OS handle (preventing PID
1412
+ // reuse); without a held handle, rely solely on a creation time captured while the relay held the handle.
1413
+ // When neither is available, do not kill — leave the broker to its own idle exit, matching main.
1414
+ const childStart =
1415
+ spawned.started ?? (spawned.holdsProcessHandle ? await readProcessCreationTime(spawned.pid) : undefined);
1416
+ if (childStart !== undefined) {
1417
+ abandoned = { kind: "announced", pid: spawned.pid, started: childStart };
1418
+ } else if (spawned.holdsProcessHandle) {
1419
+ abandoned = { kind: "handle", kill: () => spawned.killHandle() };
1420
+ }
1421
+ } else {
1422
+ abandoned = { kind: "group", pid: spawned.pid };
684
1423
  }
1424
+ if (abandoned !== undefined) {
1425
+ await stopStartingBroker(abandoned);
1426
+ }
1427
+ reject(toError(error));
1428
+ return;
685
1429
  }
1430
+ // A broker still starting keeps the lock, so later spawners wait for it instead of starting another.
1431
+ // Only now does the lock name the broker: until this hand-off it follows this live spawner, so no other
1432
+ // spawner can judge it stale and replace it while this one may still release it.
1433
+ // On Windows, hand off only when the broker's identity is verified or its OS handle is still held (#6133).
1434
+ const canHandOffLock =
1435
+ starting && (process.platform !== "win32" || spawned.started !== undefined || spawned.holdsProcessHandle);
1436
+ keepLock =
1437
+ canHandOffLock &&
1438
+ (await handSpawnLockToBrokerAsync(
1439
+ spawned.pid,
1440
+ lockOwner,
1441
+ spawned.started ??
1442
+ (spawned.holdsProcessHandle && spawned.pid !== undefined
1443
+ ? await lockProcessStartAsync(spawned.pid)
1444
+ : undefined),
1445
+ ));
1446
+ reject(toError(error));
1447
+ } finally {
1448
+ spawned.release();
686
1449
  }
687
- if (abandoned !== undefined) {
688
- void stopStartingBroker(abandoned).finally(() => reject(toError(error)));
689
- return;
690
- }
691
- // A broker still starting keeps the lock, so later spawners wait for it instead of starting another.
692
- // Only now does the lock name the broker: until this hand-off it follows this live spawner, so no other
693
- // spawner can judge it stale and replace it while this one may still release it.
694
- // The Windows launcher hides the broker's pid, so its lock could only follow this live spawner and would
695
- // block every later spawn; there the broker's own live-socket check is what prevents a takeover.
696
- // The child has not been reaped, so its pid still names it: its start is read now.
697
- keepLock =
698
- starting &&
699
- (await handSpawnLockToBrokerAsync(
700
- child.pid,
701
- lockOwner,
702
- child.pid === undefined ? undefined : await lockProcessStartAsync(child.pid),
703
- ));
704
- reject(toError(error));
705
1450
  });
706
1451
  });
707
1452
  try {
@@ -722,26 +1467,29 @@ const STARTING_BROKER_KILL_POLL_MS = 10;
722
1467
  /** A broker that has not started listening, as the spawner that launched it finds it. */
723
1468
  type StartingBroker =
724
1469
  /**
725
- * Spawned directly and detached, so it leads a process group of its own. A custom broker command can run the broker
726
- * as its own child rather than replacing itself with it; the group holds both. Its pid is read while the spawner's
727
- * child has not been reaped, so it still names that child.
1470
+ * Spawned directly and detached on POSIX, so it leads a process group of its own. A custom broker command can run the
1471
+ * broker as its own child rather than replacing itself with it; the group holds both.
728
1472
  */
729
1473
  | { readonly kind: "group"; readonly pid: number }
730
- /** Behind the Windows launcher: the pid the broker announced, and when that process was created. */
731
- | { readonly kind: "announced"; readonly pid: number; readonly started: string };
1474
+ /** Windows: verified by the process's pid and kernel creation time, so descendants are ended without PID-reuse risk. */
1475
+ | { readonly kind: "announced"; readonly pid: number; readonly started: string }
1476
+ /** Windows last-resort fallback when neither native nor PowerShell could read creation time: kill through the live child handle. */
1477
+ | { readonly kind: "handle"; readonly kill: () => void };
732
1478
 
733
1479
  /**
734
1480
  * Kill a broker that has not started listening, with every process it started, and wait until they are gone.
735
1481
  *
736
- * #6133: on Windows the broker is found by the pid it announced, which Windows gives to another process within seconds
737
- * once the broker has exited. It is stopped only through a handle to the process whose creation time is the one it
738
- * announced ({@link stopWindowsProcess}), never by its pid alone; a pid that names another process, or a process this
739
- * one may not open, counts as a broker that has already exited.
1482
+ * #6133: on Windows the broker is ended only through a handle verified against its creation time
1483
+ * ({@link stopWindowsProcess}) or directly through the live child handle, never by its pid alone.
740
1484
  */
741
1485
  async function stopStartingBroker(broker: StartingBroker): Promise<void> {
742
1486
  if (broker.kind === "announced") {
743
1487
  return stopWindowsProcess(broker.pid, broker.started, { waitMs: STARTING_BROKER_KILL_WAIT_MS, descendants: true });
744
1488
  }
1489
+ if (broker.kind === "handle") {
1490
+ broker.kill();
1491
+ return;
1492
+ }
745
1493
  const deadline = Date.now() + STARTING_BROKER_KILL_WAIT_MS;
746
1494
  try {
747
1495
  process.kill(-broker.pid, "SIGKILL");