@automaton-labs/aib 0.0.6 → 0.0.8

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 (586) hide show
  1. package/README.md +36 -257
  2. package/config/agent-dx-policy.default.json +31 -0
  3. package/config/control-plane-client.default.json +3 -0
  4. package/dist/agent-dx/agent-dx.js +805 -0
  5. package/dist/agent-dx/presentation.js +32 -0
  6. package/dist/alias-advisor/analyze.js +982 -0
  7. package/dist/alias-advisor/exact-text-cost.js +74 -0
  8. package/dist/alias-advisor/lexical.js +240 -0
  9. package/dist/alias-advisor/model.js +2 -0
  10. package/dist/alias-advisor/path-identity.js +49 -0
  11. package/dist/alias-advisor/ranking.js +171 -0
  12. package/dist/alias-advisor/token-estimator.js +85 -0
  13. package/dist/bin/aib.js +5 -1
  14. package/dist/bin/cli.js +811 -2
  15. package/dist/commands/add-missing-imports-preview-cache.js +99 -2
  16. package/dist/commands/add-missing-imports.js +241 -2
  17. package/dist/commands/apply-module-plan.js +1319 -3
  18. package/dist/commands/background-command.js +378 -0
  19. package/dist/commands/captured-input.js +74 -2
  20. package/dist/commands/config-command.js +314 -2
  21. package/dist/commands/config-output.js +357 -10
  22. package/dist/commands/control-plane-command.js +183 -0
  23. package/dist/commands/declaration-command.js +1209 -0
  24. package/dist/commands/declaration-execution-cache.js +79 -0
  25. package/dist/commands/declaration-format.js +221 -0
  26. package/dist/commands/declaration-preview-cache.js +114 -0
  27. package/dist/commands/diagnostics-command.js +70 -3
  28. package/dist/commands/doctor.js +137 -2
  29. package/dist/commands/execution-command.js +117 -1
  30. package/dist/commands/exports-star-collapse-command.js +178 -0
  31. package/dist/commands/exports-star-command.js +252 -0
  32. package/dist/commands/exports-star-preview-cache.js +84 -0
  33. package/dist/commands/feedback-command.js +176 -3
  34. package/dist/commands/file-move-to-dir-execution-cache.js +92 -0
  35. package/dist/commands/file-move-to-dir-preview-cache.js +125 -0
  36. package/dist/commands/file-move-to-dir-worker.js +54 -0
  37. package/dist/commands/file-move-to-dir.js +1073 -0
  38. package/dist/commands/file-mutation-runtime.js +102 -0
  39. package/dist/commands/file-mutation-worker-apply.js +180 -0
  40. package/dist/commands/file-refactor-batch-execution-cache.js +90 -0
  41. package/dist/commands/file-refactor-batch-preview-cache.js +125 -0
  42. package/dist/commands/file-refactor-batch-worker.js +54 -0
  43. package/dist/commands/file-refactor-batch.js +1154 -0
  44. package/dist/commands/file-rename-execution-cache.js +92 -0
  45. package/dist/commands/file-rename-preview-cache.js +125 -0
  46. package/dist/commands/file-rename-worker.js +54 -0
  47. package/dist/commands/file-rename.js +1053 -0
  48. package/dist/commands/file-text-edit-executor.js +205 -0
  49. package/dist/commands/find-importers.js +52 -1
  50. package/dist/commands/find-unused-imports.js +55 -1
  51. package/dist/commands/generate-docs-command.js +244 -6
  52. package/dist/commands/help-command.js +460 -7
  53. package/dist/commands/import-specifier-policy.js +391 -0
  54. package/dist/commands/imports-command.js +68 -1
  55. package/dist/commands/imports-rebase.js +1138 -0
  56. package/dist/commands/init-skill-usage.js +92 -3
  57. package/dist/commands/init-workspace.js +30 -1
  58. package/dist/commands/inspect-alias-candidates.js +413 -0
  59. package/dist/commands/inspect-cycles.js +811 -5
  60. package/dist/commands/inspect-direct-usages.js +98 -0
  61. package/dist/commands/inspect-duplicates-format.js +229 -0
  62. package/dist/commands/inspect-format-primitives.js +127 -0
  63. package/dist/commands/inspect-format.js +1590 -18
  64. package/dist/commands/inspect-graph.js +1553 -9
  65. package/dist/commands/inspect-imports.js +339 -2
  66. package/dist/commands/inspect-mixed-format.js +524 -0
  67. package/dist/commands/inspect-module-plan-format.js +216 -0
  68. package/dist/commands/inspect-module-plan-serialization.js +402 -0
  69. package/dist/commands/inspect-reference-path-format.js +157 -0
  70. package/dist/commands/inspect-request-values.js +599 -0
  71. package/dist/commands/inspect-selector-kind.js +21 -0
  72. package/dist/commands/inspect-selector.js +50 -0
  73. package/dist/commands/inspect-symbol-format.js +90 -0
  74. package/dist/commands/inspect-topology.js +435 -0
  75. package/dist/commands/inspect-tree.js +827 -5
  76. package/dist/commands/inspect-usages-detail.js +793 -0
  77. package/dist/commands/inspect-usages-evidence.js +31 -0
  78. package/dist/commands/inspect-usages-format.js +367 -0
  79. package/dist/commands/inspect.js +1450 -16
  80. package/dist/commands/internal-command.js +64 -0
  81. package/dist/commands/json-file-input.js +60 -1
  82. package/dist/commands/module-plan-cache.js +156 -2
  83. package/dist/commands/module-plan-standalone.js +208 -0
  84. package/dist/commands/module-plan-timeout.js +77 -1
  85. package/dist/commands/move-preview-cache.js +101 -2
  86. package/dist/commands/mutate-aggregate-output.js +996 -0
  87. package/dist/commands/mutate-child-execution.js +374 -0
  88. package/dist/commands/mutate-command.js +1394 -0
  89. package/dist/commands/mutate-declaration-output.js +313 -0
  90. package/dist/commands/mutate-domain-adapters.js +638 -0
  91. package/dist/commands/mutate-execution-cache.js +114 -0
  92. package/dist/commands/mutate-execution-status.js +598 -0
  93. package/dist/commands/mutate-failure-output.js +531 -0
  94. package/dist/commands/mutate-file-view.js +151 -0
  95. package/dist/commands/mutate-object-output.js +91 -0
  96. package/dist/commands/mutate-output-values.js +97 -0
  97. package/dist/commands/mutate-preview-cache.js +86 -0
  98. package/dist/commands/mutate-response-replay.js +153 -0
  99. package/dist/commands/mutate-result-projection.js +818 -0
  100. package/dist/commands/mutation-eta.js +28 -0
  101. package/dist/commands/mutation-execution-cache.js +140 -3
  102. package/dist/commands/mutation-recovery-journal.js +195 -0
  103. package/dist/commands/normalize-imports.js +1120 -4
  104. package/dist/commands/object-pack-command.js +546 -0
  105. package/dist/commands/object-pack-preview-cache.js +88 -0
  106. package/dist/commands/observability-command.js +47 -3
  107. package/dist/commands/ota-command.js +403 -0
  108. package/dist/commands/print-config.js +10 -1
  109. package/dist/commands/quick-read.js +1113 -11
  110. package/dist/commands/refactor-batch-builder.js +265 -1
  111. package/dist/commands/refactor-batch-execution-cache.js +85 -1
  112. package/dist/commands/refactor-batch-preview-cache.js +96 -2
  113. package/dist/commands/refactor-batch.js +461 -4
  114. package/dist/commands/rename-entities.js +794 -4
  115. package/dist/commands/rename-execution-cache.js +49 -1
  116. package/dist/commands/rename-input.js +22 -1
  117. package/dist/commands/rename-polling-policy.js +68 -0
  118. package/dist/commands/rename-preview-cache.js +96 -2
  119. package/dist/commands/result-view.js +993 -6
  120. package/dist/commands/reveal-command.js +445 -5
  121. package/dist/commands/selector-suggestions.js +93 -0
  122. package/dist/commands/session-workspace.js +1836 -31
  123. package/dist/commands/shared.js +2 -1
  124. package/dist/commands/skills-command.js +315 -0
  125. package/dist/commands/sync-command.js +59 -2
  126. package/dist/commands/worker-command.js +173 -0
  127. package/dist/commands/workspace-cache.js +55 -1
  128. package/dist/config/defaults.js +26 -1
  129. package/dist/config/env-vars.js +77 -1
  130. package/dist/config/glob-match.js +44 -1
  131. package/dist/config/import-rules.js +165 -1
  132. package/dist/config/local-config.js +293 -3
  133. package/dist/config/mutation-comments.js +51 -1
  134. package/dist/config/path-aliases.js +165 -1
  135. package/dist/config/path-display.js +84 -1
  136. package/dist/config/product-storage.js +37 -1
  137. package/dist/config/request-env.js +21 -0
  138. package/dist/config/request-routing-context.js +23 -0
  139. package/dist/config/resolve-command-alias.js +74 -1
  140. package/dist/config/resolve.js +24 -1
  141. package/dist/config/tsconfig-discovery.js +113 -1
  142. package/dist/config/typescript-preferences.js +131 -0
  143. package/dist/config/workspace-root.js +310 -3
  144. package/dist/config/workspace-state.js +254 -1
  145. package/dist/content/content-bundle.js +88 -1
  146. package/dist/diagnostics/module-plan-timeline.js +75 -2
  147. package/dist/diagnostics/readiness-text.js +45 -8
  148. package/dist/dsl/aib-dsl.js +838 -1
  149. package/dist/dsl/declaration-dsl.js +264 -0
  150. package/dist/dsl/file-move-to-dir-dsl.js +123 -0
  151. package/dist/dsl/file-refactor-batch-dsl.js +203 -0
  152. package/dist/dsl/file-rename-dsl.js +135 -0
  153. package/dist/dsl/mutate-dsl.js +746 -0
  154. package/dist/help/bootstrap.bash.md +742 -0
  155. package/dist/help/bootstrap.md +236 -437
  156. package/dist/help/bootstrap.pwsh.md +742 -0
  157. package/dist/help/docs/basics.md +1 -1
  158. package/dist/help/docs/config-setup.import-normalize.md +65 -65
  159. package/dist/help/docs/config-setup.import-rules.md +6 -5
  160. package/dist/help/docs/dsl.md +4 -3
  161. package/dist/help/docs/first-setup.md +6 -5
  162. package/dist/help/docs/help-protocol.md +4 -3
  163. package/dist/help/docs/import.base.md +38 -0
  164. package/dist/help/docs/import.rebase.md +85 -0
  165. package/dist/help/docs/inspect.aliasCandidates.md +39 -0
  166. package/dist/help/docs/inspect.code.md +5 -11
  167. package/dist/help/docs/inspect.deps.md +7 -7
  168. package/dist/help/docs/inspect.file.md +10 -18
  169. package/dist/help/docs/inspect.graph.md +6 -20
  170. package/dist/help/docs/{inspect.md → inspect.shared.md} +18 -17
  171. package/dist/help/docs/modulePlan.md +24 -28
  172. package/dist/help/docs/move.md +19 -22
  173. package/dist/help/docs/moveToDir.md +46 -0
  174. package/dist/help/docs/mutate.mixed.md +34 -0
  175. package/dist/help/docs/mutation.shared.md +55 -0
  176. package/dist/help/docs/patterns.md +3 -16
  177. package/dist/help/docs/qr.md +13 -22
  178. package/dist/help/docs/quick-map.md +36 -23
  179. package/dist/help/docs/recipe.file-layout.md +15 -0
  180. package/dist/help/docs/recipe.import-boundary.md +92 -0
  181. package/dist/help/docs/recipe.safe-artifact-probing.md +68 -0
  182. package/dist/help/docs/recipe.unfamiliar-area.md +64 -0
  183. package/dist/help/docs/recipes.md +20 -0
  184. package/dist/help/docs/rename.md +19 -27
  185. package/dist/help/docs/renameFile.md +36 -0
  186. package/dist/help/docs/rg.md +22 -0
  187. package/dist/help/docs/rules.md +26 -0
  188. package/dist/help/docs/selectors.md +3 -2
  189. package/dist/help/docs/session.md +1 -1
  190. package/dist/help/dsl/bootstrap.bash.md +742 -0
  191. package/dist/help/dsl/bootstrap.md +236 -437
  192. package/dist/help/dsl/bootstrap.pwsh.md +742 -0
  193. package/dist/help/dsl/docs/basics.md +1 -1
  194. package/dist/help/dsl/docs/config-setup.import-normalize.md +65 -65
  195. package/dist/help/dsl/docs/config-setup.import-rules.md +6 -5
  196. package/dist/help/dsl/docs/dsl.md +4 -3
  197. package/dist/help/dsl/docs/first-setup.md +6 -5
  198. package/dist/help/dsl/docs/help-protocol.md +4 -3
  199. package/dist/help/dsl/docs/import.base.md +38 -0
  200. package/dist/help/dsl/docs/import.rebase.md +85 -0
  201. package/dist/help/dsl/docs/inspect.aliasCandidates.md +39 -0
  202. package/dist/help/dsl/docs/inspect.code.md +5 -11
  203. package/dist/help/dsl/docs/inspect.deps.md +7 -7
  204. package/dist/help/dsl/docs/inspect.file.md +10 -18
  205. package/dist/help/dsl/docs/inspect.graph.md +6 -20
  206. package/dist/help/dsl/docs/{inspect.md → inspect.shared.md} +18 -17
  207. package/dist/help/dsl/docs/modulePlan.md +24 -28
  208. package/dist/help/dsl/docs/move.md +19 -22
  209. package/dist/help/dsl/docs/moveToDir.md +46 -0
  210. package/dist/help/dsl/docs/mutate.mixed.md +34 -0
  211. package/dist/help/dsl/docs/mutation.shared.md +55 -0
  212. package/dist/help/dsl/docs/patterns.md +3 -16
  213. package/dist/help/dsl/docs/qr.md +13 -22
  214. package/dist/help/dsl/docs/quick-map.md +36 -23
  215. package/dist/help/dsl/docs/recipe.file-layout.md +15 -0
  216. package/dist/help/dsl/docs/recipe.import-boundary.md +92 -0
  217. package/dist/help/dsl/docs/recipe.safe-artifact-probing.md +68 -0
  218. package/dist/help/dsl/docs/recipe.unfamiliar-area.md +64 -0
  219. package/dist/help/dsl/docs/recipes.md +20 -0
  220. package/dist/help/dsl/docs/rename.md +19 -27
  221. package/dist/help/dsl/docs/renameFile.md +36 -0
  222. package/dist/help/dsl/docs/rg.md +22 -0
  223. package/dist/help/dsl/docs/rules.md +26 -0
  224. package/dist/help/dsl/docs/selectors.md +3 -2
  225. package/dist/help/dsl/docs/session.md +1 -1
  226. package/dist/help/dsl/full.md +236 -437
  227. package/dist/help/dsl/help-index.md +49 -0
  228. package/dist/help/dsl/snippets/agents.md +2 -2
  229. package/dist/help/dsl/tokens/qr.inline.examples.md +2 -0
  230. package/dist/help/dsl/tokens/stdin.examples.bash.md +8 -0
  231. package/dist/help/dsl/tokens/stdin.examples.pwsh.md +8 -0
  232. package/dist/help/dsl/tokens/stdin.examples.with-qr.bash.md +12 -0
  233. package/dist/help/dsl/tokens/stdin.examples.with-qr.pwsh.md +12 -0
  234. package/dist/help/dsl/topics/basics.md +1 -1
  235. package/dist/help/dsl/topics/config-setup.import-normalize.md +65 -65
  236. package/dist/help/dsl/topics/config-setup.import-rules.md +6 -5
  237. package/dist/help/dsl/topics/dsl.md +4 -3
  238. package/dist/help/dsl/topics/first-setup.md +6 -5
  239. package/dist/help/dsl/topics/help-protocol.md +4 -3
  240. package/dist/help/dsl/topics/import.base.md +36 -0
  241. package/dist/help/dsl/topics/import.rebase.md +83 -0
  242. package/dist/help/dsl/topics/inspect.aliasCandidates.md +37 -0
  243. package/dist/help/dsl/topics/inspect.code.md +5 -11
  244. package/dist/help/dsl/topics/inspect.deps.md +7 -7
  245. package/dist/help/dsl/topics/inspect.file.md +10 -18
  246. package/dist/help/dsl/topics/inspect.graph.md +6 -20
  247. package/dist/help/dsl/topics/{inspect.md → inspect.shared.md} +18 -17
  248. package/dist/help/dsl/topics/modulePlan.md +21 -26
  249. package/dist/help/dsl/topics/move.md +17 -18
  250. package/dist/help/dsl/topics/moveToDir.md +44 -0
  251. package/dist/help/dsl/topics/mutate.mixed.md +32 -0
  252. package/dist/help/dsl/topics/mutation.shared.md +53 -0
  253. package/dist/help/dsl/topics/patterns.md +3 -16
  254. package/dist/help/dsl/topics/qr.md +13 -22
  255. package/dist/help/dsl/topics/quick-map.md +36 -23
  256. package/dist/help/dsl/topics/recipe.file-layout.md +13 -0
  257. package/dist/help/dsl/topics/recipe.import-boundary.md +90 -0
  258. package/dist/help/dsl/topics/recipe.safe-artifact-probing.md +66 -0
  259. package/dist/help/dsl/topics/recipe.unfamiliar-area.md +62 -0
  260. package/dist/help/dsl/topics/recipes.md +18 -0
  261. package/dist/help/dsl/topics/rename.md +15 -15
  262. package/dist/help/dsl/topics/renameFile.md +34 -0
  263. package/dist/help/dsl/topics/rg.md +20 -0
  264. package/dist/help/dsl/topics/rules.md +24 -0
  265. package/dist/help/dsl/topics/selectors.md +3 -2
  266. package/dist/help/dsl/topics/session.md +1 -1
  267. package/dist/help/full.md +236 -437
  268. package/dist/help/help-index.md +49 -0
  269. package/dist/help/help-meta.json +114 -48
  270. package/dist/help/index.md +76 -87
  271. package/dist/help/snippets/agents.md +2 -2
  272. package/dist/help/tokens/qr.inline.examples.md +2 -0
  273. package/dist/help/tokens/stdin.examples.bash.md +8 -0
  274. package/dist/help/tokens/stdin.examples.pwsh.md +8 -0
  275. package/dist/help/tokens/stdin.examples.with-qr.bash.md +12 -0
  276. package/dist/help/tokens/stdin.examples.with-qr.pwsh.md +12 -0
  277. package/dist/help/topics/basics.md +1 -1
  278. package/dist/help/topics/config-setup.import-normalize.md +65 -65
  279. package/dist/help/topics/config-setup.import-rules.md +6 -5
  280. package/dist/help/topics/dsl.md +4 -3
  281. package/dist/help/topics/first-setup.md +6 -5
  282. package/dist/help/topics/help-protocol.md +4 -3
  283. package/dist/help/topics/import.base.md +36 -0
  284. package/dist/help/topics/import.rebase.md +83 -0
  285. package/dist/help/topics/inspect.aliasCandidates.md +37 -0
  286. package/dist/help/topics/inspect.code.md +5 -11
  287. package/dist/help/topics/inspect.deps.md +7 -7
  288. package/dist/help/topics/inspect.file.md +10 -18
  289. package/dist/help/topics/inspect.graph.md +6 -20
  290. package/dist/help/topics/{inspect.md → inspect.shared.md} +18 -17
  291. package/dist/help/topics/modulePlan.md +21 -26
  292. package/dist/help/topics/move.md +17 -18
  293. package/dist/help/topics/moveToDir.md +44 -0
  294. package/dist/help/topics/mutate.mixed.md +32 -0
  295. package/dist/help/topics/mutation.shared.md +53 -0
  296. package/dist/help/topics/patterns.md +3 -16
  297. package/dist/help/topics/qr.md +13 -22
  298. package/dist/help/topics/quick-map.md +36 -23
  299. package/dist/help/topics/recipe.file-layout.md +13 -0
  300. package/dist/help/topics/recipe.import-boundary.md +90 -0
  301. package/dist/help/topics/recipe.safe-artifact-probing.md +66 -0
  302. package/dist/help/topics/recipe.unfamiliar-area.md +62 -0
  303. package/dist/help/topics/recipes.md +18 -0
  304. package/dist/help/topics/rename.md +15 -15
  305. package/dist/help/topics/renameFile.md +34 -0
  306. package/dist/help/topics/rg.md +20 -0
  307. package/dist/help/topics/rules.md +24 -0
  308. package/dist/help/topics/selectors.md +3 -2
  309. package/dist/help/topics/session.md +1 -1
  310. package/dist/host/capabilities.js +56 -0
  311. package/dist/imports/standalone-import-analysis.js +602 -0
  312. package/dist/imports/standalone-import-model.js +2 -0
  313. package/dist/imports/standalone-import-process.js +66 -0
  314. package/dist/imports/standalone-import-worker.js +27 -0
  315. package/dist/imports/standalone-ts-project.js +147 -0
  316. package/dist/inspect/inspect-duplicates-service.js +526 -0
  317. package/dist/inspect/inspect-reverse-module-closure.js +338 -0
  318. package/dist/inspect/inspect-source-ranges.js +82 -0
  319. package/dist/inspect/inspect-source-shape.js +649 -0
  320. package/dist/inspect/standalone-inspect-analysis.js +319 -0
  321. package/dist/inspect/standalone-inspect-model.js +9 -0
  322. package/dist/inspect/standalone-inspect-process.js +55 -0
  323. package/dist/inspect/standalone-inspect-usages.js +274 -0
  324. package/dist/inspect/standalone-inspect-worker.js +13 -0
  325. package/dist/metrics/central-metrics.js +101 -2
  326. package/dist/mutation/concrete-edit-plan.js +157 -0
  327. package/dist/mutation/exports-star-collapse-preview.js +361 -0
  328. package/dist/mutation/exports-star-expand-apply.js +373 -0
  329. package/dist/mutation/exports-star-expand-preview.js +807 -0
  330. package/dist/mutation/file-impact-scan.js +182 -0
  331. package/dist/mutation/file-mutation-discovery.js +674 -0
  332. package/dist/mutation/file-mutation-eta.js +99 -0
  333. package/dist/mutation/file-mutation-standalone-apply.js +584 -0
  334. package/dist/mutation/file-mutation-standalone-planner.js +500 -0
  335. package/dist/mutation/file-mutation-tsserver-session.js +473 -0
  336. package/dist/mutation/mutation-estimate.js +45 -0
  337. package/dist/mutation/mutation-plan.js +467 -0
  338. package/dist/mutation/object-mutation-foundation.js +2 -0
  339. package/dist/mutation/object-mutation-partition.js +148 -0
  340. package/dist/mutation/object-pack-semantic-apply.js +507 -0
  341. package/dist/mutation/object-pack-semantic-preview.js +984 -0
  342. package/dist/mutation/object-unpack-semantic-preview.js +993 -0
  343. package/dist/mutation/package-manifest-impact.js +176 -0
  344. package/dist/mutation/rename-owner-worker-child.js +37 -0
  345. package/dist/mutation/rename-owner-worker.js +122 -0
  346. package/dist/mutation/runtime-cycle-query.js +66 -0
  347. package/dist/mutation/semantic-execution-progress.js +63 -0
  348. package/dist/mutation/semantic-export-index.js +474 -0
  349. package/dist/mutation/semantic-impact-scan.js +434 -0
  350. package/dist/mutation/semantic-model.js +2 -0
  351. package/dist/mutation/semantic-move-best-effort-planner.js +209 -0
  352. package/dist/mutation/semantic-move-config-worker-child.js +61 -0
  353. package/dist/mutation/semantic-move-config-worker.js +449 -0
  354. package/dist/mutation/semantic-move-declarations.js +94 -0
  355. package/dist/mutation/semantic-move-metrics.js +119 -0
  356. package/dist/mutation/semantic-move-model.js +2 -0
  357. package/dist/mutation/semantic-move-owner-authority.js +122 -0
  358. package/dist/mutation/semantic-move-owner-candidates.js +300 -0
  359. package/dist/mutation/semantic-move-owner-divergence-harness.js +474 -0
  360. package/dist/mutation/semantic-move-owner-divergence-runner.js +162 -0
  361. package/dist/mutation/semantic-move-plan-hash.js +56 -0
  362. package/dist/mutation/semantic-move-policy.js +360 -0
  363. package/dist/mutation/semantic-move-process.js +218 -0
  364. package/dist/mutation/semantic-move-provider-diagnostics.js +27 -0
  365. package/dist/mutation/semantic-move-standalone-engine.js +919 -0
  366. package/dist/mutation/semantic-move-standalone-planner.js +1553 -0
  367. package/dist/mutation/semantic-move-transaction.js +639 -0
  368. package/dist/mutation/semantic-mutation-engine.js +478 -0
  369. package/dist/mutation/semantic-mutation-runtime.js +521 -0
  370. package/dist/mutation/semantic-planner-retry.js +26 -0
  371. package/dist/mutation/semantic-program-roots.js +69 -0
  372. package/dist/mutation/semantic-rename-commonjs.js +229 -0
  373. package/dist/mutation/semantic-rename-config-worker-child.js +46 -0
  374. package/dist/mutation/semantic-rename-config-worker.js +498 -0
  375. package/dist/mutation/semantic-rename-locations.js +192 -0
  376. package/dist/mutation/semantic-rename-model.js +2 -0
  377. package/dist/mutation/semantic-rename-process.js +210 -0
  378. package/dist/mutation/semantic-rename-standalone-engine.js +302 -0
  379. package/dist/mutation/semantic-rename-standalone-planner.js +567 -0
  380. package/dist/mutation/semantic-rename-transaction.js +333 -0
  381. package/dist/mutation/semantic-unused-import-cleanup.js +248 -0
  382. package/dist/mutation/semantic-worker-retry.js +40 -0
  383. package/dist/mutation/semantic-workspace.js +804 -0
  384. package/dist/mutation/targeted-import-canonicalizer.js +359 -0
  385. package/dist/observability/config.js +206 -1
  386. package/dist/observability/context.js +59 -1
  387. package/dist/observability/failure-snapshot.js +124 -2
  388. package/dist/observability/recent.js +63 -2
  389. package/dist/payloads/read-stdin-json.js +212 -1
  390. package/dist/rg-wrapper/core.js +714 -0
  391. package/dist/rg-wrapper/options.js +125 -0
  392. package/dist/rtk-wrapper/core.js +144 -0
  393. package/dist/rtk-wrapper/git-safety.js +203 -0
  394. package/dist/rtk-wrapper/output-adapter.js +106 -0
  395. package/dist/runtime/buffered-process.js +114 -0
  396. package/dist/runtime/bundled-node.js +97 -1
  397. package/dist/runtime/command-lifecycle.js +2 -0
  398. package/dist/runtime/input-source.js +238 -1
  399. package/dist/runtime/node-cli-identity.js +37 -0
  400. package/dist/runtime/run-command.js +191 -1
  401. package/dist/selectors/parse-entities.js +84 -1
  402. package/dist/semantic/semantic-context-pool.js +830 -0
  403. package/dist/semantic/semantic-context-provider.js +416 -0
  404. package/dist/semantic/semantic-resident-admission.js +38 -0
  405. package/dist/semantic/semantic-worker-child.js +40 -0
  406. package/dist/semantic/semantic-worker-manager.js +460 -0
  407. package/dist/semantic/semantic-worker-protocol.js +2 -0
  408. package/dist/semantic/semantic-worker-runtime.js +38 -0
  409. package/dist/semantic/workspace-semantic-context-pools.js +136 -0
  410. package/dist/session/client.js +359 -1
  411. package/dist/session/daemon-state.js +185 -0
  412. package/dist/session/external-tool-coordinator.js +88 -0
  413. package/dist/session/external-tool-request.js +52 -0
  414. package/dist/session/lane-owner.js +116 -0
  415. package/dist/session/paths.js +71 -1
  416. package/dist/session/runtime-lifecycle.js +225 -0
  417. package/dist/session/runtime-shutdown.js +95 -0
  418. package/dist/session/server.js +1194 -8
  419. package/dist/session/session-health.js +27 -0
  420. package/dist/shared/agent-text.js +29 -1
  421. package/dist/shared/errors.js +496 -30
  422. package/dist/shared/event-loop.js +6 -1
  423. package/dist/shared/hints.js +37 -1
  424. package/dist/shared/metrics.js +43 -1
  425. package/dist/shared/presentation.js +69 -4
  426. package/dist/shared/stdin-examples.js +77 -3
  427. package/dist/shared/stdout.js +6 -2
  428. package/dist/shared/types.js +23 -1
  429. package/dist/tool-runtime/runtime-tools.js +120 -0
  430. package/dist/topology/availability.js +663 -0
  431. package/dist/topology/cache.js +130 -0
  432. package/dist/topology/candidates.js +372 -0
  433. package/dist/topology/core.js +903 -0
  434. package/dist/topology/dependency-snapshot.js +189 -0
  435. package/dist/topology/model.js +2 -0
  436. package/dist/topology/scope.js +100 -0
  437. package/dist/topology/ts-oracle-batch.js +529 -0
  438. package/dist/topology/ts-oracle-host.js +69 -0
  439. package/dist/topology/ts-oracle-model.js +2 -0
  440. package/dist/topology/ts-oracle.js +224 -0
  441. package/dist/topology/tsconfig-loader.js +105 -0
  442. package/dist/topology/workspace-project-index.js +542 -0
  443. package/dist/tracing/config.js +192 -2
  444. package/dist/tracing/failure-summary.js +100 -0
  445. package/dist/tracing/trace.js +318 -5
  446. package/dist/tsc-wrapper/core.js +697 -0
  447. package/dist/workers/control-plane/aib-control-plane-worker.cjs +80 -0
  448. package/dist/workers/control-plane/client-config.default.json +3 -0
  449. package/dist/workers/lexical-worker-child.js +27 -0
  450. package/dist/workers/lexical-worker-manager.js +394 -0
  451. package/dist/workers/lexical-worker-protocol.js +2 -0
  452. package/dist/workers/lexical-worker-runtime.js +25 -0
  453. package/dist/workers/owned-one-shot-process.js +115 -0
  454. package/dist/workers/product-storage.js +23 -0
  455. package/dist/workers/registry.js +241 -0
  456. package/package.json +8 -11
  457. package/runtimes/tools/rg/darwin-arm64/rg +0 -0
  458. package/runtimes/tools/rg/darwin-x64/rg +0 -0
  459. package/runtimes/tools/rg/linux-arm64/rg +0 -0
  460. package/runtimes/tools/rg/linux-x64/rg +0 -0
  461. package/runtimes/tools/rg/manifest.json +36 -0
  462. package/runtimes/tools/rg/win32-x64/rg.exe +0 -0
  463. package/runtimes/tools/rtk/darwin-arm64/rtk +0 -0
  464. package/runtimes/tools/rtk/darwin-x64/rtk +0 -0
  465. package/runtimes/tools/rtk/linux-arm64/rtk +0 -0
  466. package/runtimes/tools/rtk/linux-x64/rtk +0 -0
  467. package/runtimes/tools/rtk/manifest.json +36 -0
  468. package/runtimes/tools/rtk/win32-x64/rtk.exe +0 -0
  469. package/scripts/postinstall.cjs +29 -29
  470. package/scripts/provision-runtime.cjs +411 -459
  471. package/dist/client/http-client.js +0 -1
  472. package/dist/client/transport-options.js +0 -1
  473. package/dist/client/websocket-client.js +0 -1
  474. package/dist/commands/entity-resolution.js +0 -1
  475. package/dist/commands/inspect-symbol-query.js +0 -1
  476. package/dist/commands/list-instances.js +0 -1
  477. package/dist/commands/module-plan-command.js +0 -1
  478. package/dist/commands/move-command.js +0 -1
  479. package/dist/commands/move-to-file.js +0 -2
  480. package/dist/commands/ping.js +0 -1
  481. package/dist/commands/refactor-command.js +0 -1
  482. package/dist/commands/rename-command.js +0 -1
  483. package/dist/commands/runtime-command.js +0 -4
  484. package/dist/commands/runtime-info.js +0 -1
  485. package/dist/commands/validate-module-plan.js +0 -2
  486. package/dist/compatibility/policy.js +0 -1
  487. package/dist/config/auto-start-ide.js +0 -1
  488. package/dist/discovery/registry.js +0 -1
  489. package/dist/discovery/select-instance.js +0 -1
  490. package/dist/help/docs/mutation.md +0 -50
  491. package/dist/help/docs/refactor.batch.md +0 -44
  492. package/dist/help/dsl/docs/mutation.md +0 -50
  493. package/dist/help/dsl/docs/refactor.batch.md +0 -44
  494. package/dist/help/dsl/topics/mutation.md +0 -48
  495. package/dist/help/dsl/topics/refactor.batch.md +0 -33
  496. package/dist/help/json/bootstrap.md +0 -1085
  497. package/dist/help/json/docs/basics.md +0 -15
  498. package/dist/help/json/docs/config-setup.aliases.md +0 -56
  499. package/dist/help/json/docs/config-setup.excludes.md +0 -45
  500. package/dist/help/json/docs/config-setup.import-normalize.md +0 -86
  501. package/dist/help/json/docs/config-setup.import-rules.md +0 -96
  502. package/dist/help/json/docs/config-setup.tsconfigs.md +0 -33
  503. package/dist/help/json/docs/dsl.md +0 -25
  504. package/dist/help/json/docs/first-setup.md +0 -292
  505. package/dist/help/json/docs/help-format.md +0 -9
  506. package/dist/help/json/docs/help-protocol.md +0 -26
  507. package/dist/help/json/docs/imports.normalize.md +0 -47
  508. package/dist/help/json/docs/inspect.code.md +0 -41
  509. package/dist/help/json/docs/inspect.cycles.md +0 -38
  510. package/dist/help/json/docs/inspect.deps.md +0 -46
  511. package/dist/help/json/docs/inspect.duplicates.md +0 -65
  512. package/dist/help/json/docs/inspect.exports.md +0 -40
  513. package/dist/help/json/docs/inspect.file.md +0 -38
  514. package/dist/help/json/docs/inspect.graph.md +0 -139
  515. package/dist/help/json/docs/inspect.imports.md +0 -15
  516. package/dist/help/json/docs/inspect.md +0 -88
  517. package/dist/help/json/docs/inspect.members.md +0 -32
  518. package/dist/help/json/docs/inspect.tree.md +0 -32
  519. package/dist/help/json/docs/inspect.usages.md +0 -61
  520. package/dist/help/json/docs/modulePlan.md +0 -73
  521. package/dist/help/json/docs/move.md +0 -56
  522. package/dist/help/json/docs/mutation.md +0 -65
  523. package/dist/help/json/docs/patterns.md +0 -76
  524. package/dist/help/json/docs/prefs.md +0 -40
  525. package/dist/help/json/docs/qr.md +0 -37
  526. package/dist/help/json/docs/quick-map.md +0 -30
  527. package/dist/help/json/docs/refactor.batch.md +0 -72
  528. package/dist/help/json/docs/rename.md +0 -47
  529. package/dist/help/json/docs/reveal.md +0 -30
  530. package/dist/help/json/docs/selectors.md +0 -23
  531. package/dist/help/json/docs/session.md +0 -77
  532. package/dist/help/json/docs/view.md +0 -30
  533. package/dist/help/json/full.md +0 -1085
  534. package/dist/help/json/snippets/agents.md +0 -14
  535. package/dist/help/json/topics/basics.md +0 -13
  536. package/dist/help/json/topics/config-setup.aliases.md +0 -54
  537. package/dist/help/json/topics/config-setup.excludes.md +0 -43
  538. package/dist/help/json/topics/config-setup.import-normalize.md +0 -84
  539. package/dist/help/json/topics/config-setup.import-rules.md +0 -94
  540. package/dist/help/json/topics/config-setup.tsconfigs.md +0 -31
  541. package/dist/help/json/topics/dsl.md +0 -23
  542. package/dist/help/json/topics/first-setup.md +0 -290
  543. package/dist/help/json/topics/help-format.md +0 -7
  544. package/dist/help/json/topics/help-protocol.md +0 -24
  545. package/dist/help/json/topics/imports.normalize.md +0 -45
  546. package/dist/help/json/topics/inspect.code.md +0 -39
  547. package/dist/help/json/topics/inspect.cycles.md +0 -36
  548. package/dist/help/json/topics/inspect.deps.md +0 -44
  549. package/dist/help/json/topics/inspect.duplicates.md +0 -37
  550. package/dist/help/json/topics/inspect.exports.md +0 -38
  551. package/dist/help/json/topics/inspect.file.md +0 -36
  552. package/dist/help/json/topics/inspect.graph.md +0 -137
  553. package/dist/help/json/topics/inspect.imports.md +0 -13
  554. package/dist/help/json/topics/inspect.md +0 -86
  555. package/dist/help/json/topics/inspect.members.md +0 -30
  556. package/dist/help/json/topics/inspect.tree.md +0 -22
  557. package/dist/help/json/topics/inspect.usages.md +0 -59
  558. package/dist/help/json/topics/modulePlan.md +0 -60
  559. package/dist/help/json/topics/move.md +0 -46
  560. package/dist/help/json/topics/mutation.md +0 -63
  561. package/dist/help/json/topics/patterns.md +0 -74
  562. package/dist/help/json/topics/prefs.md +0 -38
  563. package/dist/help/json/topics/qr.md +0 -35
  564. package/dist/help/json/topics/quick-map.md +0 -28
  565. package/dist/help/json/topics/refactor.batch.md +0 -61
  566. package/dist/help/json/topics/rename.md +0 -42
  567. package/dist/help/json/topics/reveal.md +0 -28
  568. package/dist/help/json/topics/selectors.md +0 -21
  569. package/dist/help/json/topics/session.md +0 -59
  570. package/dist/help/json/topics/view.md +0 -28
  571. package/dist/help/topics/mutation.md +0 -48
  572. package/dist/help/topics/refactor.batch.md +0 -33
  573. package/dist/ide-launch/common.cjs +0 -162
  574. package/dist/managed-host/extension-vsix-resolver.js +0 -1
  575. package/dist/managed-host/manage-serve-web-host.cjs +0 -141
  576. package/dist/managed-host/serve-web-autostart.js +0 -1
  577. package/dist/managed-host/serve-web-host.cjs +0 -1904
  578. package/dist/runtime/managed-runtime-provisioning.js +0 -1
  579. package/dist/shared/diagnostic-catalog.js +0 -1
  580. package/dist/shared/diagnostics.js +0 -1
  581. package/dist/shared/operations.js +0 -1
  582. package/dist/shared/protocol.js +0 -1
  583. package/dist/shared/routes.js +0 -1
  584. package/extension/vscode-refactor-bridge-extension.vsix +0 -0
  585. package/runtimes/launcher/linux-x64/aib +0 -0
  586. package/runtimes/launcher/win-x64/aib.exe +0 -0
@@ -1,1904 +0,0 @@
1
- #!/usr/bin/env node
2
-
3
- const crypto = require("node:crypto");
4
- const fs = require("node:fs");
5
- const net = require("node:net");
6
- const os = require("node:os");
7
- const path = require("node:path");
8
- const { spawn, spawnSync } = require("node:child_process");
9
- const {
10
- defaultFixtureDir,
11
- defaultVsixPath,
12
- prepareSpawnCommand,
13
- readRegistryEntries,
14
- resolveIdeCommand,
15
- rootDir,
16
- run,
17
- sleep,
18
- timestampForPath,
19
- writeJson
20
- } = require("../ide-launch/common.cjs");
21
-
22
- const managedRootDir = path.join(os.tmpdir(), "aib", "managed-hosts");
23
- const defaultRunsDir = path.join(rootDir, ".tmp", "managed-host-runs");
24
-
25
- function normalizeForId(value) {
26
- return path.resolve(String(value)).replace(/[\\/]+$/, "").toLowerCase();
27
- }
28
-
29
- function normalizeForCompare(value) {
30
- return path.normalize(String(value)).replace(/[\\/]+$/, "").toLowerCase();
31
- }
32
-
33
- function hashShort(value) {
34
- return crypto.createHash("sha1").update(value).digest("hex").slice(0, 16);
35
- }
36
-
37
- function fingerprintFile(filePath) {
38
- if (!filePath || !fs.existsSync(filePath)) {
39
- return null;
40
- }
41
-
42
- const stat = fs.statSync(filePath);
43
- const hash = crypto.createHash("sha1").update(fs.readFileSync(filePath)).digest("hex");
44
- return {
45
- path: path.resolve(filePath),
46
- hash,
47
- shortHash: hash.slice(0, 12),
48
- size: stat.size,
49
- mtimeMs: stat.mtimeMs
50
- };
51
- }
52
-
53
- function fingerprintsMatch(left, right) {
54
- if (!left || !right) {
55
- return false;
56
- }
57
-
58
- return left.hash === right.hash && left.size === right.size;
59
- }
60
-
61
- function buildHostId(options) {
62
- const hostKind = options.hostKind ?? "vscode-serve-web";
63
- return `${hostKind}-${hashShort(normalizeForId(options.fixture ?? defaultFixtureDir))}`;
64
- }
65
-
66
- function getHostDir(hostId) {
67
- return path.join(managedRootDir, hostId);
68
- }
69
-
70
- function getMetadataPath(hostId) {
71
- return path.join(getHostDir(hostId), "metadata.json");
72
- }
73
-
74
- function getWatchdogPath(hostId) {
75
- return path.join(getHostDir(hostId), "watchdog.json");
76
- }
77
-
78
- function getLockDir(hostId) {
79
- return path.join(getHostDir(hostId), "lock");
80
- }
81
-
82
- function ensureDir(dirPath) {
83
- fs.mkdirSync(dirPath, { recursive: true });
84
- }
85
-
86
- function writeText(filePath, value) {
87
- ensureDir(path.dirname(filePath));
88
- fs.writeFileSync(filePath, value);
89
- }
90
-
91
- function appendText(filePath, value) {
92
- ensureDir(path.dirname(filePath));
93
- fs.appendFileSync(filePath, value);
94
- }
95
-
96
- function writeJsonAtomic(filePath, payload) {
97
- ensureDir(path.dirname(filePath));
98
- const tempPath = `${filePath}.${process.pid}.${Date.now()}.tmp`;
99
- try {
100
- fs.writeFileSync(tempPath, `${JSON.stringify(payload, null, 2)}\n`);
101
- fs.renameSync(tempPath, filePath);
102
- } catch (error) {
103
- try {
104
- fs.rmSync(tempPath, { force: true });
105
- } catch {
106
- // Best-effort cleanup only.
107
- }
108
- throw error;
109
- }
110
- }
111
-
112
- function tail(text, maxLength = 4000) {
113
- return text.length > maxLength ? text.slice(text.length - maxLength) : text;
114
- }
115
-
116
- function readTextIfExists(filePath) {
117
- try {
118
- return fs.readFileSync(filePath, "utf8");
119
- } catch {
120
- return "";
121
- }
122
- }
123
-
124
- function readRecentLogText(root, maxFiles = 12, maxLength = 4000) {
125
- if (!fs.existsSync(root)) {
126
- return "";
127
- }
128
- const files = [];
129
- collectFiles(root, files, 5);
130
- return files
131
- .filter((filePath) => filePath.endsWith(".log") || filePath.endsWith(".txt"))
132
- .sort((left, right) => {
133
- const leftTime = fs.statSync(left).mtimeMs;
134
- const rightTime = fs.statSync(right).mtimeMs;
135
- return rightTime - leftTime;
136
- })
137
- .slice(0, maxFiles)
138
- .map((filePath) => readTextIfExists(filePath))
139
- .join("\n")
140
- .slice(-maxLength);
141
- }
142
-
143
- function collectFiles(root, files, maxDepth) {
144
- if (maxDepth < 0) {
145
- return;
146
- }
147
- let entries;
148
- try {
149
- entries = fs.readdirSync(root, { withFileTypes: true });
150
- } catch {
151
- return;
152
- }
153
- for (const entry of entries) {
154
- const entryPath = path.join(root, entry.name);
155
- if (entry.isFile()) {
156
- files.push(entryPath);
157
- } else if (entry.isDirectory()) {
158
- collectFiles(entryPath, files, maxDepth - 1);
159
- }
160
- }
161
- }
162
-
163
- function isProcessAlive(pid) {
164
- if (!Number.isInteger(pid) || pid <= 0) {
165
- return false;
166
- }
167
-
168
- try {
169
- process.kill(pid, 0);
170
- return true;
171
- } catch {
172
- return false;
173
- }
174
- }
175
-
176
- function workspaceMatchesFixture(entry, fixture) {
177
- const expected = normalizeForCompare(fixture);
178
- return (entry.workspaceFolders ?? []).some(
179
- (workspaceFolder) => normalizeForCompare(workspaceFolder) === expected
180
- );
181
- }
182
-
183
- function resolveChromePath(explicitPath) {
184
- const candidates = [
185
- explicitPath,
186
- findPackagedBrowserRuntime(),
187
- "C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe",
188
- "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe",
189
- "C:\\Program Files\\Microsoft\\Edge\\Application\\msedge.exe",
190
- "C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe",
191
- "google-chrome",
192
- "google-chrome-stable",
193
- "chromium",
194
- "chromium-browser",
195
- "microsoft-edge"
196
- ].filter(Boolean);
197
-
198
- return candidates.find((candidate) => commandOrFileExists(candidate)) ?? null;
199
- }
200
-
201
- function findPackagedBrowserRuntime() {
202
- const roots = [
203
- path.join(rootDir, "runtimes", "browser"),
204
- path.join(rootDir, "runtimes", "chrome"),
205
- path.join(rootDir, "runtimes", "chromium")
206
- ];
207
- const executableNames = process.platform === "win32"
208
- ? new Set(["chrome.exe", "chromium.exe", "msedge.exe"])
209
- : new Set(["chrome", "chromium"]);
210
- for (const runtimeRoot of roots) {
211
- const found = findFirstExecutable(runtimeRoot, executableNames, 5);
212
- if (found) {
213
- return found;
214
- }
215
- }
216
- return null;
217
- }
218
-
219
- function findFirstExecutable(root, executableNames, maxDepth) {
220
- if (!fs.existsSync(root) || maxDepth < 0) {
221
- return null;
222
- }
223
- let entries;
224
- try {
225
- entries = fs.readdirSync(root, { withFileTypes: true });
226
- } catch {
227
- return null;
228
- }
229
- for (const entry of entries) {
230
- const entryPath = path.join(root, entry.name);
231
- if (entry.isFile() && executableNames.has(entry.name) && commandOrFileExists(entryPath)) {
232
- return entryPath;
233
- }
234
- }
235
- for (const entry of entries) {
236
- if (!entry.isDirectory()) {
237
- continue;
238
- }
239
- const found = findFirstExecutable(path.join(root, entry.name), executableNames, maxDepth - 1);
240
- if (found) {
241
- return found;
242
- }
243
- }
244
- return null;
245
- }
246
-
247
- function commandOrFileExists(candidate) {
248
- if (candidate.includes("\\") || candidate.includes("/") || /^[A-Za-z]:/.test(candidate)) {
249
- return fs.existsSync(candidate);
250
- }
251
-
252
- const escaped = String(candidate).replace(/"/g, '\\"');
253
- const result = process.platform === "win32"
254
- ? spawnSync("where.exe", [candidate], { encoding: "utf8", windowsHide: true, stdio: ["ignore", "pipe", "pipe"] })
255
- : spawnSync("sh", ["-lc", `command -v "${escaped}"`], { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] });
256
- return result.status === 0;
257
- }
258
-
259
- function ideCommandEnv() {
260
- return {
261
- ...process.env,
262
- DONT_PROMPT_WSL_INSTALL: process.env.DONT_PROMPT_WSL_INSTALL ?? "1"
263
- };
264
- }
265
-
266
- function makeCommandSpec(command, prefixArgs = [], source = "command") {
267
- return {
268
- command,
269
- prefixArgs,
270
- source,
271
- displayCommand: [command, ...prefixArgs].join(" ")
272
- };
273
- }
274
-
275
- function resolvePackagedNodeRuntime() {
276
- const envNodePath = process.env.AIB_NODE_PATH;
277
- if (envNodePath && commandOrFileExists(envNodePath)) {
278
- return { command: path.resolve(envNodePath), source: "env-node" };
279
- }
280
-
281
- const platformDir = nodeRuntimePlatformDir();
282
- if (!platformDir) {
283
- return { command: process.execPath, source: "process-node" };
284
- }
285
-
286
- const candidateRoots = [
287
- path.join(rootDir, "runtimes", "node", platformDir),
288
- path.join(rootDir, "packages", "cli", "runtimes", "node", platformDir)
289
- ];
290
- for (const candidateRoot of candidateRoots) {
291
- const candidate = process.platform === "win32"
292
- ? path.join(candidateRoot, "node.exe")
293
- : path.join(candidateRoot, "bin", "node");
294
- if (fs.existsSync(candidate)) {
295
- return { command: candidate, source: "packaged-node" };
296
- }
297
- }
298
-
299
- return { command: process.execPath, source: "process-node" };
300
- }
301
-
302
- function nodeRuntimePlatformDir() {
303
- const arch = process.arch;
304
- if (process.platform === "win32" && arch === "x64") {
305
- return "win-x64";
306
- }
307
- if (process.platform === "linux" && arch === "x64") {
308
- return "linux-x64";
309
- }
310
- if (process.platform === "linux" && arch === "arm64") {
311
- return "linux-arm64";
312
- }
313
- if (process.platform === "darwin" && arch === "x64") {
314
- return "darwin-x64";
315
- }
316
- if (process.platform === "darwin" && arch === "arm64") {
317
- return "darwin-arm64";
318
- }
319
- return null;
320
- }
321
-
322
- function commandDisplayName(commandSpec) {
323
- return typeof commandSpec === "string" ? commandSpec : commandSpec.displayCommand;
324
- }
325
-
326
- function commandExecutable(commandSpec) {
327
- return typeof commandSpec === "string" ? commandSpec : commandSpec.command;
328
- }
329
-
330
- function commandArgs(commandSpec, args) {
331
- return typeof commandSpec === "string" ? args : [...commandSpec.prefixArgs, ...args];
332
- }
333
-
334
- function runCommand(commandSpec, args, options = {}) {
335
- return run(commandExecutable(commandSpec), commandArgs(commandSpec, args), options);
336
- }
337
-
338
- function startLoggedCommand(commandSpec, args, options) {
339
- return startLoggedProcess(commandExecutable(commandSpec), commandArgs(commandSpec, args), options);
340
- }
341
-
342
- function resolvePackagedCodeServerCommand() {
343
- const nodeRuntime = resolvePackagedNodeRuntime();
344
- const candidates = [
345
- {
346
- packageRoot: rootDir,
347
- entryPath: path.join(rootDir, "runtimes", "code-server", "node_modules", "code-server", "out", "node", "entry.js")
348
- },
349
- {
350
- packageRoot: path.join(rootDir, "packages", "cli"),
351
- entryPath: path.join(rootDir, "packages", "cli", "runtimes", "code-server", "node_modules", "code-server", "out", "node", "entry.js")
352
- }
353
- ];
354
- for (const { packageRoot, entryPath } of candidates) {
355
- if (fs.existsSync(entryPath) && managedRuntimePlatformStatus(packageRoot).ok) {
356
- return makeCommandSpec(nodeRuntime.command, [entryPath], nodeRuntime.source === "packaged-node"
357
- ? "packaged-code-server-entry-bundled-node"
358
- : "packaged-code-server-entry");
359
- }
360
- }
361
- return null;
362
- }
363
-
364
- function managedRuntimePlatformStatus(packageRoot) {
365
- const markerPath = path.join(packageRoot, "runtimes", ".aib-runtime-platform.json");
366
- const expectedPlatformKey = `${process.platform}-${process.arch}`;
367
- if (!fs.existsSync(markerPath)) {
368
- return { ok: true, reason: "missing", expectedPlatformKey, actualPlatformKey: null };
369
- }
370
- try {
371
- const marker = JSON.parse(fs.readFileSync(markerPath, "utf8"));
372
- const actualPlatformKey = typeof marker.platformKey === "string"
373
- ? marker.platformKey
374
- : typeof marker.platform === "string" && typeof marker.arch === "string"
375
- ? `${marker.platform}-${marker.arch}`
376
- : null;
377
- return {
378
- ok: actualPlatformKey === expectedPlatformKey,
379
- reason: actualPlatformKey === expectedPlatformKey ? "ok" : "mismatch",
380
- expectedPlatformKey,
381
- actualPlatformKey
382
- };
383
- } catch {
384
- return { ok: false, reason: "invalid", expectedPlatformKey, actualPlatformKey: null };
385
- }
386
- }
387
-
388
- function resolveManagedHostKind(options, commandSpec) {
389
- const raw = options.hostKind ?? process.env.AIB_MANAGED_HOST_KIND ?? "";
390
- if (raw) {
391
- if (raw !== "vscode-serve-web" && raw !== "code-server") {
392
- throw new Error("Expected managed host kind to be vscode-serve-web or code-server.");
393
- }
394
- return raw;
395
- }
396
-
397
- const command = commandDisplayName(commandSpec);
398
- const commandName = path.basename(String(command)).toLowerCase();
399
- return commandName === "code-server"
400
- || commandName === "code-server.cmd"
401
- || command.endsWith(path.join("code-server", "out", "node", "entry.js"))
402
- ? "code-server"
403
- : "vscode-serve-web";
404
- }
405
-
406
- function resolveManagedIdeCommand(options) {
407
- if (options.ideCommand) {
408
- return makeCommandSpec(options.ideCommand, [], "explicit");
409
- }
410
-
411
- const rawHostKind = options.hostKind ?? process.env.AIB_MANAGED_HOST_KIND ?? "";
412
- if (rawHostKind === "code-server") {
413
- if (process.env.AIB_CODE_SERVER_PATH && commandOrFileExists(process.env.AIB_CODE_SERVER_PATH)) {
414
- return makeCommandSpec(process.env.AIB_CODE_SERVER_PATH, [], "env-code-server");
415
- }
416
- const packagedCommand = resolvePackagedCodeServerCommand();
417
- if (packagedCommand) {
418
- return packagedCommand;
419
- }
420
- const candidates = [
421
- path.join(rootDir, "runtimes", "code-server", "bin", process.platform === "win32" ? "code-server.cmd" : "code-server"),
422
- path.join(rootDir, "runtimes", "code-server", "bin", "code-server"),
423
- path.join(rootDir, "packages", "cli", "runtimes", "code-server", "bin", process.platform === "win32" ? "code-server.cmd" : "code-server"),
424
- path.join(rootDir, "packages", "cli", "runtimes", "code-server", "bin", "code-server"),
425
- "code-server"
426
- ].filter(Boolean);
427
- const found = candidates.find((candidate) => commandOrFileExists(candidate)) ?? "code-server";
428
- return makeCommandSpec(found, [], "code-server-path");
429
- }
430
-
431
- return makeCommandSpec(resolveIdeCommand({ ide: "code" }), [], "vscode-code");
432
- }
433
-
434
- function buildIdeCommandEnv(runDir) {
435
- const env = ideCommandEnv();
436
- if (process.platform !== "win32") {
437
- const homeDir = path.join(runDir, "home");
438
- env.HOME = homeDir;
439
- env.VSCODE_CLI_DATA_DIR = path.join(runDir, "cli-data");
440
- }
441
- return env;
442
- }
443
-
444
- function readJsonFile(filePath) {
445
- try {
446
- return JSON.parse(fs.readFileSync(filePath, "utf8"));
447
- } catch {
448
- return null;
449
- }
450
- }
451
-
452
- function readMetadataByHostId(hostId) {
453
- const metadataPath = getMetadataPath(hostId);
454
- const metadata = fs.existsSync(metadataPath) ? readJsonFile(metadataPath) : null;
455
- if (!metadata || typeof metadata !== "object") {
456
- return null;
457
- }
458
- return metadata;
459
- }
460
-
461
- function readAllManagedHostEntries() {
462
- if (!fs.existsSync(managedRootDir)) {
463
- return [];
464
- }
465
- const entries = [];
466
- for (const item of fs.readdirSync(managedRootDir, { withFileTypes: true })) {
467
- if (!item.isDirectory()) {
468
- continue;
469
- }
470
- const metadata = readMetadataByHostId(item.name);
471
- if (!metadata) {
472
- continue;
473
- }
474
- entries.push({
475
- hostId: item.name,
476
- metadata
477
- });
478
- }
479
- return entries.sort((left, right) => String(left.hostId).localeCompare(String(right.hostId)));
480
- }
481
-
482
- function compactRuntimeStatus(status, metadata = {}) {
483
- return {
484
- hostId: status.hostId ?? metadata.hostId ?? null,
485
- hostKind: status.hostKind ?? metadata.hostKind ?? null,
486
- running: status.running === true,
487
- healthy: status.healthy === true,
488
- fixture: metadata.fixture ?? status.metadata?.fixture ?? null,
489
- runDir: metadata.runDir ?? status.metadata?.runDir ?? null,
490
- rootUrl: metadata.rootUrl ?? status.metadata?.rootUrl ?? null,
491
- reason: status.reason ?? null
492
- };
493
- }
494
-
495
- function writeMetadata(hostId, metadata) {
496
- writeJsonAtomic(getMetadataPath(hostId), metadata);
497
- }
498
-
499
- function removeMetadata(hostId) {
500
- fs.rmSync(getMetadataPath(hostId), { force: true });
501
- }
502
-
503
- function quoteCmdArg(value) {
504
- const raw = String(value);
505
- return `"${raw.replace(/%/g, "%%").replace(/"/g, '\\"')}"`;
506
- }
507
-
508
- function quotePowerShellString(value) {
509
- return `'${String(value).replace(/'/g, "''")}'`;
510
- }
511
-
512
- function writeWindowsDetachedScript(command, args, options) {
513
- ensureDir(path.dirname(options.stdoutPath));
514
- ensureDir(path.dirname(options.stderrPath));
515
- const scriptPath = `${options.stdoutPath}.cmd`;
516
- const cwd = options.cwd ?? rootDir;
517
- const commandLine = [
518
- quoteCmdArg(command),
519
- ...args.map(quoteCmdArg),
520
- ">",
521
- quoteCmdArg(options.stdoutPath),
522
- "2>",
523
- quoteCmdArg(options.stderrPath)
524
- ].join(" ");
525
- writeText(scriptPath, [
526
- "@echo off",
527
- `cd /d ${quoteCmdArg(cwd)}`,
528
- commandLine,
529
- ""
530
- ].join("\r\n"));
531
- return scriptPath;
532
- }
533
-
534
- function startWindowsHiddenScript(scriptPath, options) {
535
- const cwd = options.cwd ?? rootDir;
536
- const command = [
537
- "$p = Start-Process -FilePath 'cmd.exe'",
538
- `-ArgumentList @('/d','/s','/c', ${quotePowerShellString(scriptPath)})`,
539
- `-WorkingDirectory ${quotePowerShellString(cwd)}`,
540
- "-WindowStyle Hidden -PassThru;",
541
- "$p.Id"
542
- ].join(" ");
543
- const result = spawnSync("powershell.exe", [
544
- "-NoProfile",
545
- "-ExecutionPolicy",
546
- "Bypass",
547
- "-WindowStyle",
548
- "Hidden",
549
- "-Command",
550
- command
551
- ], {
552
- cwd,
553
- env: options.env ?? process.env,
554
- encoding: "utf8",
555
- windowsHide: true,
556
- stdio: ["ignore", "pipe", "pipe"]
557
- });
558
- if (result.status !== 0) {
559
- appendText(options.stderrPath, `${result.stdout ?? ""}${result.stderr ?? ""}${result.error ? result.error.message : ""}\n`);
560
- }
561
- const pid = Number(String(result.stdout ?? "").trim().split(/\r?\n/).pop());
562
- return {
563
- pid: Number.isFinite(pid) && pid > 0 ? pid : null,
564
- on() {},
565
- unref() {}
566
- };
567
- }
568
-
569
- function startLoggedProcess(command, args, options) {
570
- const spawnCommand = prepareSpawnCommand(command, args);
571
- if (options.detached === true && process.platform === "win32") {
572
- const scriptPath = writeWindowsDetachedScript(spawnCommand.command, spawnCommand.args, options);
573
- const child = startWindowsHiddenScript(scriptPath, options);
574
- return {
575
- child,
576
- command,
577
- args,
578
- stdoutPath: options.stdoutPath,
579
- stderrPath: options.stderrPath
580
- };
581
- }
582
-
583
- const stdoutFd = fs.openSync(options.stdoutPath, "a");
584
- const stderrFd = fs.openSync(options.stderrPath, "a");
585
- const child = spawn(spawnCommand.command, spawnCommand.args, {
586
- cwd: options.cwd ?? rootDir,
587
- env: options.env ?? process.env,
588
- detached: options.detached === true,
589
- windowsHide: true,
590
- windowsVerbatimArguments: spawnCommand.windowsVerbatimArguments ?? false,
591
- stdio: ["ignore", stdoutFd, stderrFd]
592
- });
593
-
594
- child.on("error", (error) => {
595
- appendText(options.stderrPath, `${error instanceof Error ? error.stack ?? error.message : String(error)}\n`);
596
- });
597
- if (options.detached === true) {
598
- child.unref();
599
- }
600
-
601
- return {
602
- child,
603
- command,
604
- args,
605
- stdoutPath: options.stdoutPath,
606
- stderrPath: options.stderrPath
607
- };
608
- }
609
-
610
- function stopProcessTree(pid) {
611
- if (!Number.isInteger(pid) || pid <= 0) {
612
- return {
613
- attempted: false,
614
- pid
615
- };
616
- }
617
-
618
- if (process.platform === "win32") {
619
- const result = run("taskkill.exe", ["/pid", String(pid), "/t", "/f"], { timeoutMs: 10_000 });
620
- return {
621
- attempted: true,
622
- pid,
623
- status: result.status,
624
- error: result.error,
625
- stdoutTail: tail(result.stdout, 1000),
626
- stderrTail: tail(result.stderr, 1000)
627
- };
628
- }
629
-
630
- try {
631
- if (process.platform !== "win32") {
632
- process.kill(-pid, "SIGTERM");
633
- } else {
634
- process.kill(pid, "SIGTERM");
635
- }
636
- if (process.platform !== "win32" && !waitForProcessExit(pid, 2000)) {
637
- try {
638
- process.kill(-pid, "SIGKILL");
639
- } catch {
640
- try {
641
- process.kill(pid, "SIGKILL");
642
- } catch {
643
- // Keep the SIGTERM result; this is best-effort cleanup.
644
- }
645
- }
646
- waitForProcessExit(pid, 1000);
647
- }
648
- return {
649
- attempted: true,
650
- pid,
651
- status: 0,
652
- error: null
653
- };
654
- } catch (error) {
655
- if (process.platform !== "win32") {
656
- try {
657
- process.kill(pid, "SIGTERM");
658
- if (!waitForProcessExit(pid, 2000)) {
659
- try {
660
- process.kill(pid, "SIGKILL");
661
- } catch {
662
- // Keep the SIGTERM result; this is best-effort cleanup.
663
- }
664
- waitForProcessExit(pid, 1000);
665
- }
666
- return {
667
- attempted: true,
668
- pid,
669
- status: 0,
670
- error: null
671
- };
672
- } catch {
673
- // Keep the original process-group error for diagnostics.
674
- }
675
- }
676
- return {
677
- attempted: true,
678
- pid,
679
- status: 1,
680
- error: error instanceof Error ? error.message : String(error)
681
- };
682
- }
683
- }
684
-
685
- function stopProcessesByCommandLineFragment(fragment) {
686
- if (!fragment) {
687
- return {
688
- attempted: false,
689
- fragment
690
- };
691
- }
692
- if (process.platform !== "win32") {
693
- return stopProcessesByCommandLineFragmentUnix(fragment);
694
- }
695
-
696
- const escaped = String(fragment).replace(/'/g, "''");
697
- const script = [
698
- "$self = $PID",
699
- "$fragment = '" + escaped + "'",
700
- "Get-CimInstance Win32_Process |",
701
- "Where-Object { $_.ProcessId -ne $self -and $_.CommandLine -and $_.CommandLine.Contains($fragment) } |",
702
- "ForEach-Object { try { Stop-Process -Id $_.ProcessId -Force -ErrorAction Stop; $_.ProcessId } catch {} }"
703
- ].join("\n");
704
- const result = run("powershell.exe", ["-NoProfile", "-Command", script], { timeoutMs: 10_000 });
705
- const killed = result.stdout
706
- .split(/\r?\n/)
707
- .map((line) => line.trim())
708
- .filter(Boolean).length;
709
- return {
710
- attempted: true,
711
- fragment,
712
- killed,
713
- status: result.status,
714
- error: result.error,
715
- stdoutTail: tail(result.stdout, 1000),
716
- stderrTail: tail(result.stderr, 1000)
717
- };
718
- }
719
-
720
- function stopProcessesByCommandLineFragmentUnix(fragment) {
721
- const result = run("ps", ["-eo", "pid=,args="], { timeoutMs: 10_000 });
722
- if (result.status !== 0) {
723
- return {
724
- attempted: true,
725
- fragment,
726
- killed: 0,
727
- status: result.status,
728
- error: result.error,
729
- stdoutTail: tail(result.stdout, 1000),
730
- stderrTail: tail(result.stderr, 1000)
731
- };
732
- }
733
-
734
- const currentPid = process.pid;
735
- const parentPid = process.ppid;
736
- const pids = result.stdout
737
- .split(/\r?\n/)
738
- .map((line) => {
739
- const match = line.match(/^\s*(\d+)\s+(.*)$/);
740
- if (!match) {
741
- return null;
742
- }
743
- return {
744
- pid: Number(match[1]),
745
- commandLine: match[2] ?? ""
746
- };
747
- })
748
- .filter(Boolean)
749
- .filter((row) => row.pid !== currentPid && row.pid !== parentPid)
750
- .filter((row) => row.commandLine.includes(fragment))
751
- .map((row) => row.pid);
752
-
753
- const uniquePids = [...new Set(pids)].filter((pid) => Number.isInteger(pid) && pid > 0);
754
- let killed = 0;
755
- const errors = [];
756
- for (const pid of uniquePids) {
757
- try {
758
- process.kill(pid, "SIGTERM");
759
- killed += 1;
760
- } catch (error) {
761
- errors.push(`${pid}: ${error instanceof Error ? error.message : String(error)}`);
762
- }
763
- }
764
- if (killed > 0) {
765
- sleepSync(250);
766
- }
767
- for (const pid of uniquePids) {
768
- if (!isProcessAlive(pid)) {
769
- continue;
770
- }
771
- try {
772
- process.kill(pid, "SIGKILL");
773
- } catch (error) {
774
- errors.push(`${pid}: ${error instanceof Error ? error.message : String(error)}`);
775
- }
776
- }
777
- return {
778
- attempted: true,
779
- fragment,
780
- killed,
781
- status: errors.length === 0 ? 0 : 1,
782
- error: errors.join("; ") || null
783
- };
784
- }
785
-
786
- function stopOrphanedPackagedRuntimeProcesses(activeRunDirs = []) {
787
- if (process.platform !== "win32") {
788
- return {
789
- attempted: false,
790
- reason: "unsupported-platform"
791
- };
792
- }
793
-
794
- const escapedRoot = rootDir.replace(/'/g, "''");
795
- const activeList = activeRunDirs
796
- .filter(Boolean)
797
- .map((item) => "'" + String(item).replace(/'/g, "''") + "'")
798
- .join(",");
799
- const script = [
800
- "$root = '" + escapedRoot + "'",
801
- "$active = @(" + activeList + ")",
802
- "$runtimePattern = [regex]::Escape($root + '\\runtimes\\')",
803
- "$runPattern = [regex]::Escape($root + '\\.tmp\\managed-host-runs\\')",
804
- "Get-CimInstance Win32_Process |",
805
- "Where-Object {",
806
- " $cmd = $_.CommandLine",
807
- " $cmd -and",
808
- " $cmd -match $runtimePattern -and",
809
- " $cmd -match $runPattern -and",
810
- " -not ($active | Where-Object { $_ -and $cmd.Contains($_) })",
811
- "} |",
812
- "ForEach-Object { try { Stop-Process -Id $_.ProcessId -Force -ErrorAction Stop; $_.ProcessId } catch {} }"
813
- ].join(" ");
814
- const result = run("powershell.exe", ["-NoProfile", "-Command", script], { timeoutMs: 10_000 });
815
- return {
816
- attempted: true,
817
- status: result.status,
818
- error: result.error,
819
- stdoutTail: tail(result.stdout, 1000),
820
- stderrTail: tail(result.stderr, 1000)
821
- };
822
- }
823
-
824
- function stopAibOwnedRuntimeProcesses() {
825
- if (process.platform !== "win32") {
826
- return stopAibOwnedRuntimeProcessesUnix();
827
- }
828
-
829
- const roots = [
830
- rootDir,
831
- path.join(rootDir, "packages", "cli")
832
- ].map((item) => String(item).replace(/'/g, "''"));
833
- const script = [
834
- "$roots = @(" + roots.map((item) => "'" + item + "'").join(",") + ")",
835
- "$processes = @(Get-CimInstance Win32_Process | Where-Object {",
836
- " $cmd = $_.CommandLine",
837
- " if (-not $cmd) { return $false }",
838
- " $underAibRoot = [bool]($roots | Where-Object { $_ -and $cmd.Contains($_) })",
839
- " $hasRunMarker = $cmd.Contains('managed-host-runs')",
840
- " $isAibWatchdog = $cmd.Contains('manage-serve-web-host.cjs') -and $cmd.Contains('watchdog') -and $underAibRoot",
841
- " $isPackagedRuntime = $underAibRoot -and ($cmd.Contains('\\runtimes\\code-server\\') -or $cmd.Contains('\\runtimes\\browser\\'))",
842
- " $isAibDetachedWrapper = $underAibRoot -and ($cmd.Contains('serve-web.stdout.txt.cmd') -or $cmd.Contains('headless-browser.stdout.txt.cmd') -or $cmd.Contains('watchdog.stdout.txt.cmd'))",
843
- " ($hasRunMarker -and $underAibRoot) -or $isAibWatchdog -or $isPackagedRuntime -or $isAibDetachedWrapper",
844
- "})",
845
- "$processes | ForEach-Object { try { Stop-Process -Id $_.ProcessId -Force -ErrorAction Stop; $_.ProcessId } catch {} }"
846
- ].join("\n");
847
- const result = run("powershell.exe", ["-NoProfile", "-Command", script], { timeoutMs: 15_000 });
848
- const killed = result.stdout
849
- .split(/\r?\n/)
850
- .map((line) => line.trim())
851
- .filter(Boolean).length;
852
- return {
853
- attempted: true,
854
- killed,
855
- status: result.status,
856
- error: result.error,
857
- stdoutTail: tail(result.stdout, 1000),
858
- stderrTail: tail(result.stderr, 1000)
859
- };
860
- }
861
-
862
- function stopAibOwnedRuntimeProcessesUnix() {
863
- const roots = [
864
- rootDir,
865
- path.join(rootDir, "packages", "cli")
866
- ].map((item) => String(item));
867
- const result = run("ps", ["-eo", "pid=,args="], { timeoutMs: 10_000 });
868
- if (result.status !== 0) {
869
- return {
870
- attempted: true,
871
- killed: 0,
872
- status: result.status,
873
- error: result.error,
874
- stdoutTail: tail(result.stdout, 1000),
875
- stderrTail: tail(result.stderr, 1000)
876
- };
877
- }
878
-
879
- const currentPid = process.pid;
880
- const parentPid = process.ppid;
881
- const pids = result.stdout
882
- .split(/\r?\n/)
883
- .map((line) => {
884
- const match = line.match(/^\s*(\d+)\s+(.*)$/);
885
- if (!match) {
886
- return null;
887
- }
888
- return {
889
- pid: Number(match[1]),
890
- commandLine: match[2] ?? ""
891
- };
892
- })
893
- .filter(Boolean)
894
- .filter((row) => row.pid !== currentPid && row.pid !== parentPid)
895
- .filter((row) => isAibOwnedRuntimeCommandLine(row.commandLine, roots))
896
- .map((row) => row.pid);
897
-
898
- const uniquePids = [...new Set(pids)].filter((pid) => Number.isInteger(pid) && pid > 0);
899
- let killed = 0;
900
- const errors = [];
901
- for (const pid of uniquePids) {
902
- try {
903
- process.kill(pid, "SIGTERM");
904
- killed += 1;
905
- } catch (error) {
906
- errors.push(`${pid}: ${error instanceof Error ? error.message : String(error)}`);
907
- }
908
- }
909
- if (killed > 0) {
910
- sleepSync(250);
911
- }
912
- for (const pid of uniquePids) {
913
- if (!isProcessAlive(pid)) {
914
- continue;
915
- }
916
- try {
917
- process.kill(pid, "SIGKILL");
918
- } catch (error) {
919
- errors.push(`${pid}: ${error instanceof Error ? error.message : String(error)}`);
920
- }
921
- }
922
-
923
- return {
924
- attempted: true,
925
- killed,
926
- status: errors.length === 0 ? 0 : 1,
927
- error: errors.join("; ") || null
928
- };
929
- }
930
-
931
- function isAibOwnedRuntimeCommandLine(commandLine, roots) {
932
- if (!commandLine) {
933
- return false;
934
- }
935
- const underAibRoot = roots.some((root) => root && commandLine.includes(root));
936
- if (!underAibRoot) {
937
- return false;
938
- }
939
- const hasRunMarker = commandLine.includes("managed-host-runs");
940
- const isAibWatchdog = commandLine.includes("manage-serve-web-host.cjs") && commandLine.includes("watchdog");
941
- const isPackagedRuntime =
942
- commandLine.includes("/runtimes/code-server/") ||
943
- commandLine.includes("\\runtimes\\code-server\\") ||
944
- commandLine.includes("/runtimes/browser/") ||
945
- commandLine.includes("\\runtimes\\browser\\");
946
- return hasRunMarker || isAibWatchdog || isPackagedRuntime;
947
- }
948
-
949
- function sleepSync(ms) {
950
- try {
951
- Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
952
- } catch {
953
- // Best-effort delay only.
954
- }
955
- }
956
-
957
- function waitForProcessExit(pid, timeoutMs) {
958
- const deadline = Date.now() + timeoutMs;
959
- while (Date.now() < deadline) {
960
- if (!isProcessAlive(pid)) {
961
- return true;
962
- }
963
- sleepSync(50);
964
- }
965
- return !isProcessAlive(pid);
966
- }
967
-
968
- function readTtlMs(value, fallbackMs = 15 * 60_000) {
969
- if (value === null || value === undefined || value === "") {
970
- return fallbackMs;
971
- }
972
- const parsed = Number(value);
973
- return Number.isFinite(parsed) ? parsed : fallbackMs;
974
- }
975
-
976
- function metadataLastActivityMs(metadata) {
977
- const raw = metadata?.lastActivityAt ?? metadata?.updatedAt ?? metadata?.startedAt;
978
- const parsed = typeof raw === "string" ? Date.parse(raw) : NaN;
979
- return Number.isFinite(parsed) ? parsed : 0;
980
- }
981
-
982
- function isMetadataExpired(metadata, ttlMs, now = Date.now()) {
983
- if (!Number.isFinite(ttlMs) || ttlMs <= 0) {
984
- return false;
985
- }
986
- const lastActivityMs = metadataLastActivityMs(metadata);
987
- return lastActivityMs > 0 && now - lastActivityMs > ttlMs;
988
- }
989
-
990
- async function tryFetch(url) {
991
- try {
992
- const response = await fetch(url);
993
- return {
994
- ok: response.ok,
995
- status: response.status,
996
- contentType: response.headers.get("content-type")
997
- };
998
- } catch (error) {
999
- return {
1000
- ok: false,
1001
- error: error instanceof Error ? error.message : String(error)
1002
- };
1003
- }
1004
- }
1005
-
1006
- async function waitFor(name, timeoutMs, pollMs, getState, isReady) {
1007
- const startedAt = Date.now();
1008
- const attempts = [];
1009
-
1010
- while (Date.now() - startedAt <= timeoutMs) {
1011
- const state = await getState();
1012
- attempts.push(state);
1013
- if (isReady(state)) {
1014
- return {
1015
- ok: true,
1016
- durationMs: Date.now() - startedAt,
1017
- attempts: attempts.length,
1018
- state
1019
- };
1020
- }
1021
- await sleep(pollMs);
1022
- }
1023
-
1024
- return {
1025
- ok: false,
1026
- durationMs: Date.now() - startedAt,
1027
- attempts: attempts.length,
1028
- error: `${name} did not become ready within ${timeoutMs}ms.`,
1029
- lastState: attempts.at(-1) ?? null
1030
- };
1031
- }
1032
-
1033
- async function allocatePort() {
1034
- return new Promise((resolve, reject) => {
1035
- const server = net.createServer();
1036
- server.once("error", reject);
1037
- server.listen(0, "127.0.0.1", () => {
1038
- const address = server.address();
1039
- const port = address && typeof address === "object" ? address.port : null;
1040
- server.close(() => {
1041
- if (Number.isInteger(port)) {
1042
- resolve(port);
1043
- } else {
1044
- reject(new Error("Failed to allocate a TCP port."));
1045
- }
1046
- });
1047
- });
1048
- });
1049
- }
1050
-
1051
- async function acquireLock(hostId, timeoutMs = 15_000, staleMs = 120_000) {
1052
- const lockDir = getLockDir(hostId);
1053
- const startedAt = Date.now();
1054
- ensureDir(path.dirname(lockDir));
1055
-
1056
- while (Date.now() - startedAt <= timeoutMs) {
1057
- try {
1058
- fs.mkdirSync(lockDir);
1059
- writeJson(path.join(lockDir, "owner.json"), {
1060
- pid: process.pid,
1061
- acquiredAt: new Date().toISOString()
1062
- });
1063
- return {
1064
- hostId,
1065
- lockDir,
1066
- release() {
1067
- fs.rmSync(lockDir, { recursive: true, force: true });
1068
- }
1069
- };
1070
- } catch (error) {
1071
- if (error && error.code === "EEXIST") {
1072
- const owner = readJsonFile(path.join(lockDir, "owner.json"));
1073
- const ownerPid = Number.isInteger(owner?.pid) ? owner.pid : null;
1074
- const ownerAlive = ownerPid !== null && isProcessAlive(ownerPid);
1075
- const stat = fs.statSync(lockDir);
1076
- if ((ownerPid !== null && !ownerAlive) || Date.now() - stat.mtimeMs > staleMs) {
1077
- fs.rmSync(lockDir, { recursive: true, force: true });
1078
- continue;
1079
- }
1080
- await sleep(250);
1081
- continue;
1082
- }
1083
- throw error;
1084
- }
1085
- }
1086
-
1087
- throw new Error(`Timed out acquiring managed host lock: ${lockDir}`);
1088
- }
1089
-
1090
- function getMatchingRegistryEntry(metadata) {
1091
- if (!metadata || typeof metadata.instanceId !== "string") {
1092
- return null;
1093
- }
1094
-
1095
- return readRegistryEntries().find((entry) => entry.instanceId === metadata.instanceId) ?? null;
1096
- }
1097
-
1098
- async function getManagedServeWebHostStatus(options = {}) {
1099
- if (options.all === true) {
1100
- return getAllManagedServeWebHostStatuses(options);
1101
- }
1102
-
1103
- const fixture = path.resolve(options.fixture ?? defaultFixtureDir);
1104
- const codeCommand = resolveManagedIdeCommand(options);
1105
- const hostKind = resolveManagedHostKind(options, codeCommand);
1106
- const hostId = options.hostId ?? buildHostId({ fixture, hostKind });
1107
- const expectedVsix = options.vsix ? fingerprintFile(path.resolve(options.vsix)) : null;
1108
- const metadata = readMetadataByHostId(hostId);
1109
- if (!metadata) {
1110
- return {
1111
- ok: true,
1112
- hostId,
1113
- running: false,
1114
- healthy: false,
1115
- reason: "metadata-not-found"
1116
- };
1117
- }
1118
-
1119
- const registryEntry = getMatchingRegistryEntry(metadata);
1120
- const rootUrl = metadata.rootUrl ?? (Number.isInteger(metadata.port) ? `http://127.0.0.1:${metadata.port}` : null);
1121
- const http = rootUrl ? await tryFetch(rootUrl) : { ok: false, error: "missing rootUrl" };
1122
- const serveWebAlive = isProcessAlive(metadata.serveWebPid);
1123
- const browserAlive = isProcessAlive(metadata.browserPid);
1124
- const extensionHostAlive = registryEntry ? isProcessAlive(registryEntry.pid) : false;
1125
- const workspaceMatches = registryEntry ? workspaceMatchesFixture(registryEntry, fixture) : false;
1126
- const vsixMatches = expectedVsix ? fingerprintsMatch(metadata.vsixFingerprint, expectedVsix) : true;
1127
- const healthy = serveWebAlive && browserAlive && extensionHostAlive && http.ok === true && workspaceMatches && vsixMatches;
1128
-
1129
- return {
1130
- ok: true,
1131
- hostId,
1132
- running: serveWebAlive || browserAlive || extensionHostAlive,
1133
- healthy,
1134
- metadata,
1135
- health: {
1136
- serveWebAlive,
1137
- browserAlive,
1138
- extensionHostAlive,
1139
- workspaceMatches,
1140
- vsixMatches,
1141
- expectedVsix,
1142
- http,
1143
- registryEntry
1144
- }
1145
- };
1146
- }
1147
-
1148
- async function getAllManagedServeWebHostStatuses(options = {}) {
1149
- const entries = readAllManagedHostEntries();
1150
- const runtimes = [];
1151
- for (const entry of entries) {
1152
- const metadata = entry.metadata;
1153
- const status = await getManagedServeWebHostStatus({
1154
- ...options,
1155
- all: false,
1156
- hostId: entry.hostId,
1157
- fixture: metadata.fixture ?? defaultFixtureDir,
1158
- vsix: metadata.vsix,
1159
- hostKind: metadata.hostKind
1160
- });
1161
- runtimes.push(compactRuntimeStatus(status, metadata));
1162
- }
1163
- return {
1164
- ok: true,
1165
- all: true,
1166
- count: runtimes.length,
1167
- running: runtimes.filter((runtime) => runtime.running === true).length,
1168
- healthy: runtimes.filter((runtime) => runtime.healthy === true).length,
1169
- runtimes
1170
- };
1171
- }
1172
-
1173
- async function startManagedServeWebHost(options = {}) {
1174
- const startedAt = Date.now();
1175
- const fixture = path.resolve(options.fixture ?? defaultFixtureDir);
1176
- const ttlMs = readTtlMs(options.ttlMs);
1177
- const intervalMs = Number.isFinite(Number(options.intervalMs)) && Number(options.intervalMs) > 0
1178
- ? Number(options.intervalMs)
1179
- : 30_000;
1180
- const waitMs = Number.isInteger(options.waitMs) ? options.waitMs : 45_000;
1181
- const pollMs = Number.isInteger(options.pollMs) ? options.pollMs : 500;
1182
- const vsix = path.resolve(options.vsix ?? defaultVsixPath);
1183
- const vsixFingerprint = fingerprintFile(vsix);
1184
- const reuse = options.reuse !== false;
1185
- const codeCommand = resolveManagedIdeCommand(options);
1186
- const hostKind = resolveManagedHostKind(options, codeCommand);
1187
- const hostId = options.hostId ?? buildHostId({ fixture, hostKind });
1188
- const runDir = path.resolve(options.runDir ?? path.join(defaultRunsDir, `${hostId}-${timestampForPath()}`));
1189
- const logsDir = path.join(runDir, "logs");
1190
- const stepsDir = path.join(runDir, "steps");
1191
- const userDataDir = path.join(runDir, "user-data");
1192
- const serverDataDir = path.join(runDir, "server-data");
1193
- const extensionsDir = path.join(runDir, "extensions");
1194
- const activeExtensionsDir = hostKind === "code-server" || process.platform === "win32"
1195
- ? extensionsDir
1196
- : path.join(serverDataDir, "extensions");
1197
- const ideEnv = buildIdeCommandEnv(runDir);
1198
- const steps = [];
1199
- const failures = [];
1200
- const beforeRegistry = readRegistryEntries();
1201
- const beforeInstanceIds = new Set(beforeRegistry.map((entry) => entry.instanceId));
1202
- let serveWebProcess = null;
1203
- let browserProcess = null;
1204
- let metadata = null;
1205
-
1206
- ensureDir(logsDir);
1207
- ensureDir(stepsDir);
1208
- await cleanupExpiredManagedServeWebHosts({ ttlMs });
1209
-
1210
- async function step(name, fn) {
1211
- const stepIndex = String(steps.length + 1).padStart(2, "0");
1212
- const stepPath = path.join(stepsDir, `${stepIndex}-${name.replace(/[^a-z0-9]+/gi, "-").toLowerCase()}.json`);
1213
- const startedStepAt = Date.now();
1214
- const record = {
1215
- name,
1216
- ok: false,
1217
- startedAt: new Date(startedStepAt).toISOString()
1218
- };
1219
-
1220
- try {
1221
- record.detail = await fn();
1222
- record.ok = record.detail?.ok !== false;
1223
- if (!record.ok) {
1224
- failures.push(`${name}: ${record.detail?.error ?? "failed"}`);
1225
- }
1226
- } catch (error) {
1227
- record.ok = false;
1228
- record.error = error instanceof Error ? error.message : String(error);
1229
- failures.push(`${name}: ${record.error}`);
1230
- } finally {
1231
- record.durationMs = Date.now() - startedStepAt;
1232
- record.finishedAt = new Date().toISOString();
1233
- record.path = stepPath;
1234
- writeJson(stepPath, record);
1235
- steps.push(record);
1236
- }
1237
-
1238
- return record;
1239
- }
1240
-
1241
- const lock = await acquireLock(hostId, Math.max(90_000, waitMs + 45_000));
1242
- try {
1243
- const orphanCleanup = readMetadataByHostId(hostId) ? null : stopProcessesByCommandLineFragment(hostId);
1244
- if (reuse) {
1245
- const existingStatus = await getManagedServeWebHostStatus({ fixture, hostId, vsix, ideCommand: options.ideCommand, hostKind });
1246
- if (existingStatus.healthy) {
1247
- const updatedMetadata = {
1248
- ...existingStatus.metadata,
1249
- updatedAt: new Date().toISOString(),
1250
- lastActivityAt: new Date().toISOString(),
1251
- ttlMs,
1252
- watchdogIntervalMs: intervalMs
1253
- };
1254
- writeMetadata(hostId, updatedMetadata);
1255
- startManagedServeWebWatchdog({ fixture, hostId, ttlMs, intervalMs, logsDir: existingStatus.metadata.logsDir ?? logsDir, ideCommand: options.ideCommand, hostKind });
1256
- return buildStartSummary({
1257
- ok: true,
1258
- reused: true,
1259
- startedAt,
1260
- hostId,
1261
- fixture,
1262
- vsix,
1263
- codeCommand,
1264
- hostKind,
1265
- runDir: existingStatus.metadata.runDir ?? runDir,
1266
- logsDir: existingStatus.metadata.logsDir ?? logsDir,
1267
- stepsDir: existingStatus.metadata.stepsDir ?? stepsDir,
1268
- metadata: updatedMetadata,
1269
- steps,
1270
- failures,
1271
- orphanCleanup
1272
- });
1273
- }
1274
- if (existingStatus.metadata) {
1275
- await stopManagedServeWebHost({ fixture, hostId, removeMetadataOnlyIfKnown: true });
1276
- }
1277
- } else {
1278
- await stopManagedServeWebHost({ fixture, hostId, removeMetadataOnlyIfKnown: true });
1279
- }
1280
-
1281
- await step("prepare profile", async () => {
1282
- ensureDir(path.join(runDir, "home"));
1283
- ensureDir(path.join(runDir, "cli-data"));
1284
- ensureDir(path.join(userDataDir, "User"));
1285
- ensureDir(path.join(serverDataDir, "data", "User"));
1286
- ensureDir(serverDataDir);
1287
- ensureDir(extensionsDir);
1288
- ensureDir(activeExtensionsDir);
1289
- const settings = {
1290
- "security.workspace.trust.enabled": false,
1291
- "workbench.startupEditor": "none"
1292
- };
1293
- writeJson(path.join(userDataDir, "User", "settings.json"), settings);
1294
- writeJson(path.join(serverDataDir, "data", "User", "settings.json"), settings);
1295
- return {
1296
- ok: true,
1297
- runDir,
1298
- userDataDir,
1299
- serverDataDir,
1300
- extensionsDir
1301
- };
1302
- });
1303
-
1304
- await step("install extension", async () => {
1305
- if (!fs.existsSync(vsix)) {
1306
- return {
1307
- ok: false,
1308
- error: `VSIX does not exist: ${vsix}`
1309
- };
1310
- }
1311
- const result = runCommand(codeCommand, [
1312
- "--extensions-dir",
1313
- activeExtensionsDir,
1314
- "--install-extension",
1315
- vsix,
1316
- "--force"
1317
- ], { timeoutMs: 60_000, env: ideEnv });
1318
- const stdoutPath = path.join(logsDir, "install-extension.stdout.txt");
1319
- const stderrPath = path.join(logsDir, "install-extension.stderr.txt");
1320
- writeText(stdoutPath, result.stdout);
1321
- writeText(stderrPath, result.stderr);
1322
- return {
1323
- ok: result.status === 0,
1324
- status: result.status,
1325
- durationMs: result.durationMs,
1326
- stdoutPath,
1327
- stderrPath,
1328
- stdoutTail: tail(result.stdout),
1329
- stderrTail: tail(result.stderr),
1330
- error: result.error
1331
- };
1332
- });
1333
- if (failures.length > 0) {
1334
- return buildStartSummary({ ok: false, reused: false, startedAt, hostId, fixture, vsix, codeCommand, hostKind, runDir, logsDir, stepsDir, metadata, steps, failures, orphanCleanup });
1335
- }
1336
-
1337
- const port = Number.isInteger(options.port) ? options.port : await allocatePort();
1338
- const rootUrl = `http://127.0.0.1:${port}`;
1339
-
1340
- const serveWebStdoutPath = path.join(logsDir, "serve-web.stdout.txt");
1341
- const serveWebStderrPath = path.join(logsDir, "serve-web.stderr.txt");
1342
-
1343
- await step("start serve-web", async () => {
1344
- const args = hostKind === "code-server"
1345
- ? [
1346
- "--auth",
1347
- "none",
1348
- "--bind-addr",
1349
- `127.0.0.1:${port}`,
1350
- "--disable-workspace-trust",
1351
- "--disable-telemetry",
1352
- "--disable-update-check",
1353
- "--user-data-dir",
1354
- userDataDir,
1355
- "--extensions-dir",
1356
- activeExtensionsDir,
1357
- fixture
1358
- ]
1359
- : [
1360
- "--user-data-dir",
1361
- userDataDir,
1362
- ...(process.platform === "win32" ? ["--extensions-dir", activeExtensionsDir] : []),
1363
- "serve-web",
1364
- "--accept-server-license-terms",
1365
- "--host",
1366
- "127.0.0.1",
1367
- "--port",
1368
- String(port),
1369
- "--without-connection-token",
1370
- "--default-folder",
1371
- fixture,
1372
- "--server-data-dir",
1373
- serverDataDir,
1374
- "--log",
1375
- "trace",
1376
- ...(process.platform !== "win32" ? ["--cli-data-dir", ideEnv.VSCODE_CLI_DATA_DIR ?? path.join(runDir, "cli-data")] : [])
1377
- ];
1378
- serveWebProcess = startLoggedCommand(codeCommand, args, {
1379
- stdoutPath: serveWebStdoutPath,
1380
- stderrPath: serveWebStderrPath,
1381
- detached: true,
1382
- env: ideEnv
1383
- });
1384
- return {
1385
- ok: true,
1386
- pid: serveWebProcess.child.pid ?? null,
1387
- command: commandDisplayName(codeCommand),
1388
- commandSource: codeCommand.source ?? null,
1389
- hostKind,
1390
- args,
1391
- stdoutPath: serveWebStdoutPath,
1392
- stderrPath: serveWebStderrPath
1393
- };
1394
- });
1395
-
1396
- await step("wait for serve-web http", async () => {
1397
- return waitFor(
1398
- "serve-web http",
1399
- waitMs,
1400
- pollMs,
1401
- () => tryFetch(rootUrl),
1402
- (state) => state.ok === true
1403
- );
1404
- });
1405
-
1406
- await step("wait for extension host agent", async () => {
1407
- return waitFor(
1408
- "extension host agent",
1409
- waitMs,
1410
- pollMs,
1411
- () => {
1412
- const stdout = readTextIfExists(serveWebStdoutPath);
1413
- const stderr = readTextIfExists(serveWebStderrPath);
1414
- const userDataLogs = readRecentLogText(path.join(userDataDir, "logs"));
1415
- const serverDataLogs = readRecentLogText(path.join(serverDataDir, "logs"));
1416
- const combined = `${stdout}\n${stderr}\n${userDataLogs}\n${serverDataLogs}`;
1417
- return {
1418
- ready: combined.includes("Extension host agent started")
1419
- || combined.includes("Extension host agent listening"),
1420
- stdoutTail: tail(stdout, 1000),
1421
- stderrTail: tail(stderr, 1000),
1422
- logTail: tail(`${userDataLogs}\n${serverDataLogs}`, 1000)
1423
- };
1424
- },
1425
- (state) => state.ready === true
1426
- );
1427
- });
1428
- if (failures.length > 0) {
1429
- stopProcessTree(serveWebProcess?.child?.pid);
1430
- return buildStartSummary({ ok: false, reused: false, startedAt, hostId, fixture, vsix, codeCommand, hostKind, runDir, logsDir, stepsDir, metadata, steps, failures, orphanCleanup });
1431
- }
1432
-
1433
- await step("open headless browser client", async () => {
1434
- const chromePath = resolveChromePath(options.chromePath);
1435
- if (!chromePath) {
1436
- return {
1437
- ok: false,
1438
- error: "Chrome or Edge executable was not found."
1439
- };
1440
- }
1441
-
1442
- const profileDir = path.join(runDir, "headless-browser-profile");
1443
- const stdoutPath = path.join(logsDir, "headless-browser.stdout.txt");
1444
- const stderrPath = path.join(logsDir, "headless-browser.stderr.txt");
1445
- const url = `${rootUrl}/?folder=${encodeURIComponent(fixture)}`;
1446
- const browserArgs = [
1447
- "--headless=new",
1448
- "--disable-gpu",
1449
- "--disable-dev-shm-usage",
1450
- "--disable-background-networking",
1451
- "--disable-sync",
1452
- "--no-sandbox",
1453
- "--remote-debugging-port=0",
1454
- "--no-first-run",
1455
- "--no-default-browser-check",
1456
- `--user-data-dir=${profileDir}`,
1457
- url
1458
- ];
1459
- if (process.platform === "win32") {
1460
- const scriptPath = writeWindowsDetachedScript(chromePath, browserArgs, {
1461
- cwd: rootDir,
1462
- stdoutPath,
1463
- stderrPath
1464
- });
1465
- browserProcess = startWindowsHiddenScript(scriptPath, {
1466
- cwd: rootDir,
1467
- stdoutPath,
1468
- stderrPath
1469
- });
1470
- } else {
1471
- const stdoutFd = fs.openSync(stdoutPath, "a");
1472
- const stderrFd = fs.openSync(stderrPath, "a");
1473
- browserProcess = spawn(chromePath, browserArgs, {
1474
- cwd: rootDir,
1475
- detached: true,
1476
- windowsHide: true,
1477
- stdio: ["ignore", stdoutFd, stderrFd]
1478
- });
1479
- }
1480
- browserProcess.on("error", () => {
1481
- // Later registry/health waits surface browser startup failures.
1482
- });
1483
- browserProcess.unref();
1484
-
1485
- return {
1486
- ok: true,
1487
- pid: browserProcess.pid ?? null,
1488
- chromePath,
1489
- profileDir,
1490
- devToolsActivePortPath: path.join(profileDir, "DevToolsActivePort"),
1491
- stdoutPath,
1492
- stderrPath,
1493
- url
1494
- };
1495
- });
1496
-
1497
- await step("wait for bridge registry entry", async () => {
1498
- const waitResult = await waitFor(
1499
- "fresh bridge registry entry",
1500
- waitMs,
1501
- pollMs,
1502
- () => {
1503
- const entries = readRegistryEntries();
1504
- const matchingFreshEntries = entries.filter(
1505
- (entry) => !beforeInstanceIds.has(entry.instanceId) && workspaceMatchesFixture(entry, fixture)
1506
- );
1507
- return {
1508
- ok: matchingFreshEntries.length > 0,
1509
- entry: matchingFreshEntries[0] ?? null,
1510
- entryCount: entries.length,
1511
- matchingFreshCount: matchingFreshEntries.length
1512
- };
1513
- },
1514
- (state) => state.ok === true
1515
- );
1516
- return waitResult;
1517
- });
1518
- if (failures.length > 0) {
1519
- stopProcessTree(browserProcess?.pid);
1520
- stopProcessTree(serveWebProcess?.child?.pid);
1521
- return buildStartSummary({ ok: false, reused: false, startedAt, hostId, fixture, vsix, codeCommand, hostKind, runDir, logsDir, stepsDir, metadata, steps, failures, orphanCleanup });
1522
- }
1523
-
1524
- const registryEntry = steps.at(-1)?.detail?.state?.entry ?? null;
1525
- metadata = {
1526
- hostId,
1527
- kind: "serve-web-headless-client",
1528
- hostKind,
1529
- fixture,
1530
- vsix,
1531
- vsixFingerprint,
1532
- codeCommand: commandDisplayName(codeCommand),
1533
- codeCommandSource: codeCommand.source ?? null,
1534
- runDir,
1535
- logsDir,
1536
- stepsDir,
1537
- port,
1538
- rootUrl,
1539
- serveWebPid: serveWebProcess?.child?.pid ?? null,
1540
- browserPid: browserProcess?.pid ?? null,
1541
- instanceId: registryEntry?.instanceId ?? null,
1542
- registryPath: registryEntry?.registryPath ?? null,
1543
- workspaceFolders: registryEntry?.workspaceFolders ?? [],
1544
- startedAt: new Date(startedAt).toISOString(),
1545
- updatedAt: new Date().toISOString()
1546
- };
1547
- metadata.lastActivityAt = metadata.updatedAt;
1548
- metadata.ttlMs = ttlMs;
1549
- metadata.watchdogIntervalMs = intervalMs;
1550
- writeMetadata(hostId, metadata);
1551
- startManagedServeWebWatchdog({ fixture, hostId, ttlMs, intervalMs, logsDir, ideCommand: options.ideCommand, hostKind });
1552
-
1553
- return buildStartSummary({
1554
- ok: true,
1555
- reused: false,
1556
- startedAt,
1557
- hostId,
1558
- fixture,
1559
- vsix,
1560
- codeCommand: commandDisplayName(codeCommand),
1561
- codeCommandSource: codeCommand.source ?? null,
1562
- hostKind,
1563
- runDir,
1564
- logsDir,
1565
- stepsDir,
1566
- metadata,
1567
- registryEntry,
1568
- steps,
1569
- failures,
1570
- orphanCleanup
1571
- });
1572
- } finally {
1573
- lock.release();
1574
- }
1575
- }
1576
-
1577
- async function stopManagedServeWebHost(options = {}) {
1578
- if (options.all === true) {
1579
- return stopAllManagedServeWebHosts(options);
1580
- }
1581
-
1582
- const fixture = path.resolve(options.fixture ?? defaultFixtureDir);
1583
- const codeCommand = resolveManagedIdeCommand(options);
1584
- const hostKind = resolveManagedHostKind(options, codeCommand);
1585
- const hostId = options.hostId ?? buildHostId({ fixture, hostKind });
1586
- const metadata = readMetadataByHostId(hostId);
1587
- if (!metadata) {
1588
- const orphanCleanup = stopProcessesByCommandLineFragment(hostId);
1589
- return {
1590
- ok: true,
1591
- hostId,
1592
- hostKind,
1593
- stopped: (orphanCleanup.killed ?? 0) > 0,
1594
- reason: (orphanCleanup.killed ?? 0) > 0 ? "orphan-processes-stopped" : "metadata-not-found",
1595
- orphanCleanup
1596
- };
1597
- }
1598
-
1599
- const stopResults = [];
1600
- const watchdog = readJsonFile(getWatchdogPath(hostId));
1601
- if (watchdog && Number.isInteger(watchdog.pid) && watchdog.pid !== process.pid) {
1602
- stopResults.push({
1603
- name: "watchdog",
1604
- ...stopProcessTree(watchdog.pid)
1605
- });
1606
- }
1607
- if (Number.isInteger(metadata.browserPid)) {
1608
- stopResults.push({
1609
- name: "headless-browser",
1610
- ...stopProcessTree(metadata.browserPid)
1611
- });
1612
- }
1613
- if (Number.isInteger(metadata.serveWebPid)) {
1614
- stopResults.push({
1615
- name: "serve-web",
1616
- ...stopProcessTree(metadata.serveWebPid)
1617
- });
1618
- }
1619
- if (typeof metadata.runDir === "string") {
1620
- stopResults.push({
1621
- name: "run-dir-processes",
1622
- ...stopProcessesByCommandLineFragment(metadata.runDir)
1623
- });
1624
- }
1625
-
1626
- let registryCleanup = {
1627
- removed: false,
1628
- path: metadata.registryPath ?? null
1629
- };
1630
- if (typeof metadata.registryPath === "string") {
1631
- try {
1632
- fs.rmSync(metadata.registryPath, { force: true });
1633
- registryCleanup = {
1634
- removed: true,
1635
- path: metadata.registryPath
1636
- };
1637
- } catch (error) {
1638
- registryCleanup = {
1639
- removed: false,
1640
- path: metadata.registryPath,
1641
- error: error instanceof Error ? error.message : String(error)
1642
- };
1643
- }
1644
- }
1645
-
1646
- removeMetadata(hostId);
1647
- fs.rmSync(getWatchdogPath(hostId), { force: true });
1648
- return {
1649
- ok: true,
1650
- hostId,
1651
- hostKind: metadata.hostKind ?? hostKind,
1652
- stopped: true,
1653
- metadata,
1654
- stopResults,
1655
- registryCleanup
1656
- };
1657
- }
1658
-
1659
- async function stopAllManagedServeWebHosts(options = {}) {
1660
- const entries = readAllManagedHostEntries();
1661
- const stopped = [];
1662
- for (const entry of entries) {
1663
- const metadata = entry.metadata;
1664
- const result = await stopManagedServeWebHost({
1665
- ...options,
1666
- all: false,
1667
- hostId: entry.hostId,
1668
- fixture: metadata.fixture ?? defaultFixtureDir,
1669
- hostKind: metadata.hostKind
1670
- });
1671
- stopped.push({
1672
- hostId: entry.hostId,
1673
- hostKind: result.hostKind ?? metadata.hostKind ?? null,
1674
- fixture: metadata.fixture ?? null,
1675
- runDir: metadata.runDir ?? null,
1676
- stopped: result.stopped === true,
1677
- reason: result.reason ?? null
1678
- });
1679
- }
1680
- return {
1681
- ok: true,
1682
- all: true,
1683
- count: stopped.length,
1684
- stopped: stopped.filter((item) => item.stopped === true).length,
1685
- runtimes: stopped
1686
- };
1687
- }
1688
-
1689
- async function killManagedServeWebHosts(options = {}) {
1690
- if (options.all !== true) {
1691
- return {
1692
- ok: false,
1693
- code: "RUNTIME_KILL_REQUIRES_ALL",
1694
- error: "runtime kill currently requires --all."
1695
- };
1696
- }
1697
- const stopResult = await stopAllManagedServeWebHosts(options);
1698
- const orphanCleanup = stopAibOwnedRuntimeProcesses();
1699
- return {
1700
- ok: true,
1701
- all: true,
1702
- stop: stopResult,
1703
- killed: orphanCleanup.killed ?? 0,
1704
- orphanCleanup
1705
- };
1706
- }
1707
-
1708
- async function cleanupExpiredManagedServeWebHosts(options = {}) {
1709
- const ttlMs = readTtlMs(options.ttlMs);
1710
- if (!Number.isFinite(ttlMs) || ttlMs <= 0) {
1711
- return {
1712
- ok: true,
1713
- ttlMs,
1714
- stopped: []
1715
- };
1716
- }
1717
- if (!fs.existsSync(managedRootDir)) {
1718
- return {
1719
- ok: true,
1720
- ttlMs,
1721
- stopped: []
1722
- };
1723
- }
1724
-
1725
- const stopped = [];
1726
- const activeRunDirs = [];
1727
- for (const item of fs.readdirSync(managedRootDir, { withFileTypes: true })) {
1728
- if (!item.isDirectory()) {
1729
- continue;
1730
- }
1731
- const hostId = item.name;
1732
- const metadata = readMetadataByHostId(hostId);
1733
- if (!metadata || !isMetadataExpired(metadata, ttlMs)) {
1734
- if (metadata && typeof metadata.runDir === "string" && metadata.runDir.length > 0) {
1735
- activeRunDirs.push(metadata.runDir);
1736
- }
1737
- continue;
1738
- }
1739
- const result = await stopManagedServeWebHost({ hostId, fixture: metadata.fixture ?? defaultFixtureDir });
1740
- stopped.push({
1741
- hostId,
1742
- fixture: metadata.fixture ?? null,
1743
- lastActivityAt: metadata.lastActivityAt ?? metadata.updatedAt ?? null,
1744
- stopped: result.stopped === true
1745
- });
1746
- }
1747
- const orphanCleanup = stopOrphanedPackagedRuntimeProcesses(activeRunDirs);
1748
-
1749
- return {
1750
- ok: true,
1751
- ttlMs,
1752
- stopped,
1753
- orphanCleanup
1754
- };
1755
- }
1756
-
1757
- async function runManagedServeWebWatchdog(options = {}) {
1758
- const fixture = path.resolve(options.fixture ?? defaultFixtureDir);
1759
- const codeCommand = resolveManagedIdeCommand(options);
1760
- const hostKind = resolveManagedHostKind(options, codeCommand);
1761
- const hostId = options.hostId ?? buildHostId({ fixture, hostKind });
1762
- const ttlMs = readTtlMs(options.ttlMs);
1763
- const intervalMs = Number.isFinite(Number(options.intervalMs)) && Number(options.intervalMs) > 0
1764
- ? Number(options.intervalMs)
1765
- : 30_000;
1766
- if (!Number.isFinite(ttlMs) || ttlMs <= 0) {
1767
- return {
1768
- ok: true,
1769
- hostId,
1770
- hostKind,
1771
- watching: false,
1772
- reason: "ttl-disabled"
1773
- };
1774
- }
1775
-
1776
- writeJsonAtomic(getWatchdogPath(hostId), {
1777
- pid: process.pid,
1778
- hostId,
1779
- hostKind,
1780
- fixture,
1781
- ttlMs,
1782
- intervalMs,
1783
- startedAt: new Date().toISOString()
1784
- });
1785
-
1786
- while (true) {
1787
- const metadata = readMetadataByHostId(hostId);
1788
- if (!metadata) {
1789
- return {
1790
- ok: true,
1791
- hostId,
1792
- hostKind,
1793
- stopped: false,
1794
- reason: "metadata-not-found"
1795
- };
1796
- }
1797
- const status = await getManagedServeWebHostStatus({ fixture, hostId, vsix: metadata.vsix, hostKind: metadata.hostKind ?? hostKind });
1798
- if (!status.running) {
1799
- return {
1800
- ok: true,
1801
- hostId,
1802
- hostKind: metadata.hostKind ?? hostKind,
1803
- stopped: false,
1804
- reason: "not-running"
1805
- };
1806
- }
1807
- if (isMetadataExpired(metadata, ttlMs)) {
1808
- const result = await stopManagedServeWebHost({ fixture, hostId });
1809
- return {
1810
- ok: true,
1811
- hostId,
1812
- hostKind: metadata.hostKind ?? hostKind,
1813
- stopped: result.stopped === true,
1814
- reason: "ttl-expired"
1815
- };
1816
- }
1817
- await sleep(intervalMs);
1818
- }
1819
- }
1820
-
1821
- function startManagedServeWebWatchdog(options) {
1822
- const ttlMs = readTtlMs(options.ttlMs);
1823
- if (!Number.isFinite(ttlMs) || ttlMs <= 0) {
1824
- return;
1825
- }
1826
- const existing = readJsonFile(getWatchdogPath(options.hostId));
1827
- if (existing && isProcessAlive(existing.pid)) {
1828
- return;
1829
- }
1830
- const stdoutPath = path.join(options.logsDir, "watchdog.stdout.txt");
1831
- const stderrPath = path.join(options.logsDir, "watchdog.stderr.txt");
1832
- const nodeRuntime = resolvePackagedNodeRuntime();
1833
- startLoggedProcess(nodeRuntime.command, [
1834
- path.join(__dirname, "manage-serve-web-host.cjs"),
1835
- "watchdog",
1836
- "--fixture",
1837
- options.fixture,
1838
- ...(options.ideCommand ? ["--ide-command", options.ideCommand] : []),
1839
- ...(options.hostKind ? ["--host-kind", options.hostKind] : []),
1840
- "--ttl-ms",
1841
- String(ttlMs),
1842
- "--interval-ms",
1843
- String(options.intervalMs ?? 30_000)
1844
- ], {
1845
- cwd: rootDir,
1846
- detached: true,
1847
- stdoutPath,
1848
- stderrPath
1849
- });
1850
- }
1851
-
1852
- function buildStartSummary(input) {
1853
- const codeCommand = input.codeCommand && typeof input.codeCommand === "object"
1854
- ? commandDisplayName(input.codeCommand)
1855
- : input.codeCommand;
1856
- const codeCommandSource = input.codeCommandSource
1857
- ?? (input.codeCommand && typeof input.codeCommand === "object" ? input.codeCommand.source : null);
1858
- const summaryPath = input.reused
1859
- ? path.join(input.runDir, `reuse-${timestampForPath()}.json`)
1860
- : path.join(input.runDir, "summary.json");
1861
- const summary = {
1862
- ok: input.ok,
1863
- reused: input.reused,
1864
- hostId: input.hostId,
1865
- kind: "serve-web-headless-client",
1866
- startedAt: new Date(input.startedAt).toISOString(),
1867
- finishedAt: new Date().toISOString(),
1868
- durationMs: Date.now() - input.startedAt,
1869
- fixture: input.fixture,
1870
- vsix: input.vsix,
1871
- vsixFingerprint: input.metadata?.vsixFingerprint ?? fingerprintFile(input.vsix),
1872
- codeCommand,
1873
- codeCommandSource,
1874
- hostKind: input.hostKind ?? input.metadata?.hostKind ?? "vscode-serve-web",
1875
- runDir: input.runDir,
1876
- metadata: input.metadata,
1877
- registryEntry: input.registryEntry ?? null,
1878
- artifacts: {
1879
- logsDir: input.logsDir,
1880
- stepsDir: input.stepsDir,
1881
- summaryPath
1882
- },
1883
- orphanCleanup: input.orphanCleanup ?? null,
1884
- steps: input.steps.map((record) => ({
1885
- name: record.name,
1886
- ok: record.ok,
1887
- durationMs: record.durationMs,
1888
- path: record.path
1889
- })),
1890
- failures: input.failures
1891
- };
1892
- writeJson(summaryPath, summary);
1893
- return summary;
1894
- }
1895
-
1896
- module.exports = {
1897
- buildHostId,
1898
- cleanupExpiredManagedServeWebHosts,
1899
- getManagedServeWebHostStatus,
1900
- killManagedServeWebHosts,
1901
- runManagedServeWebWatchdog,
1902
- startManagedServeWebHost,
1903
- stopManagedServeWebHost
1904
- };