@automaton-labs/aib 0.0.7 → 0.0.9

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 (477) hide show
  1. package/README.md +21 -578
  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 -4
  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 -2
  19. package/dist/commands/captured-input.js +74 -1
  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 -1
  23. package/dist/commands/declaration-command.js +1209 -7
  24. package/dist/commands/declaration-execution-cache.js +79 -1
  25. package/dist/commands/declaration-format.js +221 -1
  26. package/dist/commands/declaration-preview-cache.js +114 -2
  27. package/dist/commands/diagnostics-command.js +70 -3
  28. package/dist/commands/doctor.js +137 -3
  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 -1
  35. package/dist/commands/file-move-to-dir-preview-cache.js +125 -2
  36. package/dist/commands/file-move-to-dir-worker.js +54 -0
  37. package/dist/commands/file-move-to-dir.js +1073 -5
  38. package/dist/commands/file-mutation-runtime.js +102 -1
  39. package/dist/commands/file-mutation-worker-apply.js +180 -0
  40. package/dist/commands/file-refactor-batch-execution-cache.js +90 -1
  41. package/dist/commands/file-refactor-batch-preview-cache.js +125 -2
  42. package/dist/commands/file-refactor-batch-worker.js +54 -0
  43. package/dist/commands/file-refactor-batch.js +1154 -5
  44. package/dist/commands/file-rename-execution-cache.js +92 -1
  45. package/dist/commands/file-rename-preview-cache.js +125 -2
  46. package/dist/commands/file-rename-worker.js +54 -0
  47. package/dist/commands/file-rename.js +1053 -5
  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 -2
  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 -7
  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 -1
  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 -1
  150. package/dist/dsl/file-move-to-dir-dsl.js +123 -1
  151. package/dist/dsl/file-refactor-batch-dsl.js +203 -1
  152. package/dist/dsl/file-rename-dsl.js +135 -1
  153. package/dist/dsl/mutate-dsl.js +746 -0
  154. package/dist/help/bootstrap.bash.md +176 -341
  155. package/dist/help/bootstrap.md +175 -340
  156. package/dist/help/bootstrap.pwsh.md +176 -341
  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/first-setup.md +6 -5
  161. package/dist/help/docs/help-protocol.md +4 -3
  162. package/dist/help/docs/import.base.md +38 -0
  163. package/dist/help/docs/import.rebase.md +85 -0
  164. package/dist/help/docs/inspect.aliasCandidates.md +39 -0
  165. package/dist/help/docs/inspect.code.md +1 -7
  166. package/dist/help/docs/inspect.file.md +10 -19
  167. package/dist/help/docs/inspect.graph.md +3 -17
  168. package/dist/help/{dsl/docs/inspect.md → docs/inspect.shared.md} +13 -12
  169. package/dist/help/docs/modulePlan.md +24 -28
  170. package/dist/help/docs/move.md +19 -22
  171. package/dist/help/{dsl/topics/file.move.md → docs/moveToDir.md} +36 -34
  172. package/dist/help/docs/mutate.mixed.md +34 -0
  173. package/dist/help/docs/mutation.shared.md +55 -0
  174. package/dist/help/docs/patterns.md +3 -12
  175. package/dist/help/docs/qr.md +12 -6
  176. package/dist/help/docs/quick-map.md +36 -24
  177. package/dist/help/docs/recipe.file-layout.md +10 -10
  178. package/dist/help/docs/recipe.import-boundary.md +92 -0
  179. package/dist/help/docs/recipe.safe-artifact-probing.md +68 -0
  180. package/dist/help/docs/recipe.unfamiliar-area.md +64 -0
  181. package/dist/help/docs/recipes.md +20 -0
  182. package/dist/help/docs/rename.md +19 -27
  183. package/dist/help/docs/renameFile.md +36 -0
  184. package/dist/help/docs/rules.md +26 -0
  185. package/dist/help/dsl/bootstrap.bash.md +176 -341
  186. package/dist/help/dsl/bootstrap.md +175 -340
  187. package/dist/help/dsl/bootstrap.pwsh.md +176 -341
  188. package/dist/help/dsl/docs/basics.md +1 -1
  189. package/dist/help/dsl/docs/config-setup.import-normalize.md +65 -65
  190. package/dist/help/dsl/docs/config-setup.import-rules.md +6 -5
  191. package/dist/help/dsl/docs/first-setup.md +6 -5
  192. package/dist/help/dsl/docs/help-protocol.md +4 -3
  193. package/dist/help/dsl/docs/import.base.md +38 -0
  194. package/dist/help/dsl/docs/import.rebase.md +85 -0
  195. package/dist/help/dsl/docs/inspect.aliasCandidates.md +39 -0
  196. package/dist/help/dsl/docs/inspect.code.md +1 -7
  197. package/dist/help/dsl/docs/inspect.file.md +10 -19
  198. package/dist/help/dsl/docs/inspect.graph.md +3 -17
  199. package/dist/help/{docs/inspect.md → dsl/docs/inspect.shared.md} +13 -12
  200. package/dist/help/dsl/docs/modulePlan.md +24 -28
  201. package/dist/help/dsl/docs/move.md +19 -22
  202. package/dist/help/{topics/file.move.md → dsl/docs/moveToDir.md} +36 -34
  203. package/dist/help/dsl/docs/mutate.mixed.md +34 -0
  204. package/dist/help/dsl/docs/mutation.shared.md +55 -0
  205. package/dist/help/dsl/docs/patterns.md +3 -12
  206. package/dist/help/dsl/docs/qr.md +12 -6
  207. package/dist/help/dsl/docs/quick-map.md +36 -24
  208. package/dist/help/dsl/docs/recipe.file-layout.md +10 -10
  209. package/dist/help/dsl/docs/recipe.import-boundary.md +92 -0
  210. package/dist/help/dsl/docs/recipe.safe-artifact-probing.md +68 -0
  211. package/dist/help/dsl/docs/recipe.unfamiliar-area.md +64 -0
  212. package/dist/help/dsl/docs/recipes.md +20 -0
  213. package/dist/help/dsl/docs/rename.md +19 -27
  214. package/dist/help/dsl/docs/renameFile.md +36 -0
  215. package/dist/help/dsl/docs/rules.md +26 -0
  216. package/dist/help/dsl/full.md +175 -340
  217. package/dist/help/dsl/help-index.md +48 -43
  218. package/dist/help/dsl/snippets/agents.md +2 -2
  219. package/dist/help/dsl/tokens/qr.inline.examples.md +1 -1
  220. package/dist/help/dsl/topics/basics.md +1 -1
  221. package/dist/help/dsl/topics/config-setup.import-normalize.md +65 -65
  222. package/dist/help/dsl/topics/config-setup.import-rules.md +6 -5
  223. package/dist/help/dsl/topics/first-setup.md +6 -5
  224. package/dist/help/dsl/topics/help-protocol.md +4 -3
  225. package/dist/help/dsl/topics/import.base.md +36 -0
  226. package/dist/help/dsl/topics/import.rebase.md +83 -0
  227. package/dist/help/dsl/topics/inspect.aliasCandidates.md +37 -0
  228. package/dist/help/dsl/topics/inspect.code.md +1 -7
  229. package/dist/help/dsl/topics/inspect.file.md +10 -19
  230. package/dist/help/dsl/topics/inspect.graph.md +3 -17
  231. package/dist/help/dsl/topics/{inspect.md → inspect.shared.md} +13 -12
  232. package/dist/help/dsl/topics/modulePlan.md +21 -26
  233. package/dist/help/dsl/topics/move.md +17 -18
  234. package/dist/help/{docs/file.move.md → dsl/topics/moveToDir.md} +33 -35
  235. package/dist/help/dsl/topics/mutate.mixed.md +32 -0
  236. package/dist/help/dsl/topics/mutation.shared.md +53 -0
  237. package/dist/help/dsl/topics/patterns.md +3 -12
  238. package/dist/help/dsl/topics/qr.md +12 -6
  239. package/dist/help/dsl/topics/quick-map.md +36 -24
  240. package/dist/help/dsl/topics/recipe.file-layout.md +10 -10
  241. package/dist/help/dsl/topics/recipe.import-boundary.md +90 -0
  242. package/dist/help/dsl/topics/recipe.safe-artifact-probing.md +66 -0
  243. package/dist/help/dsl/topics/recipe.unfamiliar-area.md +62 -0
  244. package/dist/help/dsl/topics/recipes.md +18 -0
  245. package/dist/help/dsl/topics/rename.md +15 -15
  246. package/dist/help/dsl/topics/renameFile.md +34 -0
  247. package/dist/help/dsl/topics/rules.md +24 -0
  248. package/dist/help/full.md +175 -340
  249. package/dist/help/help-index.md +48 -43
  250. package/dist/help/help-meta.json +98 -48
  251. package/dist/help/index.md +52 -20
  252. package/dist/help/snippets/agents.md +2 -2
  253. package/dist/help/tokens/qr.inline.examples.md +1 -1
  254. package/dist/help/topics/basics.md +1 -1
  255. package/dist/help/topics/config-setup.import-normalize.md +65 -65
  256. package/dist/help/topics/config-setup.import-rules.md +6 -5
  257. package/dist/help/topics/first-setup.md +6 -5
  258. package/dist/help/topics/help-protocol.md +4 -3
  259. package/dist/help/topics/import.base.md +36 -0
  260. package/dist/help/topics/import.rebase.md +83 -0
  261. package/dist/help/topics/inspect.aliasCandidates.md +37 -0
  262. package/dist/help/topics/inspect.code.md +1 -7
  263. package/dist/help/topics/inspect.file.md +10 -19
  264. package/dist/help/topics/inspect.graph.md +3 -17
  265. package/dist/help/topics/{inspect.md → inspect.shared.md} +13 -12
  266. package/dist/help/topics/modulePlan.md +21 -26
  267. package/dist/help/topics/move.md +17 -18
  268. package/dist/help/{dsl/docs/file.move.md → topics/moveToDir.md} +33 -35
  269. package/dist/help/topics/mutate.mixed.md +32 -0
  270. package/dist/help/topics/mutation.shared.md +53 -0
  271. package/dist/help/topics/patterns.md +3 -12
  272. package/dist/help/topics/qr.md +12 -6
  273. package/dist/help/topics/quick-map.md +36 -24
  274. package/dist/help/topics/recipe.file-layout.md +10 -10
  275. package/dist/help/topics/recipe.import-boundary.md +90 -0
  276. package/dist/help/topics/recipe.safe-artifact-probing.md +66 -0
  277. package/dist/help/topics/recipe.unfamiliar-area.md +62 -0
  278. package/dist/help/topics/recipes.md +18 -0
  279. package/dist/help/topics/rename.md +15 -15
  280. package/dist/help/topics/renameFile.md +34 -0
  281. package/dist/help/topics/rules.md +24 -0
  282. package/dist/host/capabilities.js +56 -1
  283. package/dist/imports/standalone-import-analysis.js +602 -0
  284. package/dist/imports/standalone-import-model.js +2 -0
  285. package/dist/imports/standalone-import-process.js +66 -0
  286. package/dist/imports/standalone-import-worker.js +27 -0
  287. package/dist/imports/standalone-ts-project.js +147 -0
  288. package/dist/inspect/inspect-duplicates-service.js +526 -0
  289. package/dist/inspect/inspect-reverse-module-closure.js +338 -0
  290. package/dist/inspect/inspect-source-ranges.js +82 -0
  291. package/dist/inspect/inspect-source-shape.js +649 -0
  292. package/dist/inspect/standalone-inspect-analysis.js +319 -0
  293. package/dist/inspect/standalone-inspect-model.js +9 -0
  294. package/dist/inspect/standalone-inspect-process.js +55 -0
  295. package/dist/inspect/standalone-inspect-usages.js +274 -0
  296. package/dist/inspect/standalone-inspect-worker.js +13 -0
  297. package/dist/metrics/central-metrics.js +101 -2
  298. package/dist/mutation/concrete-edit-plan.js +157 -0
  299. package/dist/mutation/exports-star-collapse-preview.js +361 -0
  300. package/dist/mutation/exports-star-expand-apply.js +373 -0
  301. package/dist/mutation/exports-star-expand-preview.js +807 -0
  302. package/dist/mutation/file-impact-scan.js +182 -0
  303. package/dist/mutation/file-mutation-discovery.js +674 -0
  304. package/dist/mutation/file-mutation-eta.js +99 -0
  305. package/dist/mutation/file-mutation-standalone-apply.js +584 -0
  306. package/dist/mutation/file-mutation-standalone-planner.js +500 -0
  307. package/dist/mutation/file-mutation-tsserver-session.js +473 -0
  308. package/dist/mutation/mutation-estimate.js +45 -0
  309. package/dist/mutation/mutation-plan.js +467 -0
  310. package/dist/mutation/object-mutation-foundation.js +2 -0
  311. package/dist/mutation/object-mutation-partition.js +148 -0
  312. package/dist/mutation/object-pack-semantic-apply.js +507 -0
  313. package/dist/mutation/object-pack-semantic-preview.js +984 -0
  314. package/dist/mutation/object-unpack-semantic-preview.js +993 -0
  315. package/dist/mutation/package-manifest-impact.js +176 -0
  316. package/dist/mutation/rename-owner-worker-child.js +37 -0
  317. package/dist/mutation/rename-owner-worker.js +122 -0
  318. package/dist/mutation/runtime-cycle-query.js +66 -0
  319. package/dist/mutation/semantic-execution-progress.js +63 -0
  320. package/dist/mutation/semantic-export-index.js +474 -0
  321. package/dist/mutation/semantic-impact-scan.js +434 -0
  322. package/dist/mutation/semantic-model.js +2 -0
  323. package/dist/mutation/semantic-move-best-effort-planner.js +209 -0
  324. package/dist/mutation/semantic-move-config-worker-child.js +61 -0
  325. package/dist/mutation/semantic-move-config-worker.js +449 -0
  326. package/dist/mutation/semantic-move-declarations.js +94 -0
  327. package/dist/mutation/semantic-move-metrics.js +119 -0
  328. package/dist/mutation/semantic-move-model.js +2 -0
  329. package/dist/mutation/semantic-move-owner-authority.js +122 -0
  330. package/dist/mutation/semantic-move-owner-candidates.js +300 -0
  331. package/dist/mutation/semantic-move-owner-divergence-harness.js +474 -0
  332. package/dist/mutation/semantic-move-owner-divergence-runner.js +162 -0
  333. package/dist/mutation/semantic-move-plan-hash.js +56 -0
  334. package/dist/mutation/semantic-move-policy.js +360 -0
  335. package/dist/mutation/semantic-move-process.js +218 -0
  336. package/dist/mutation/semantic-move-provider-diagnostics.js +27 -0
  337. package/dist/mutation/semantic-move-standalone-engine.js +919 -0
  338. package/dist/mutation/semantic-move-standalone-planner.js +1553 -0
  339. package/dist/mutation/semantic-move-transaction.js +639 -0
  340. package/dist/mutation/semantic-mutation-engine.js +478 -0
  341. package/dist/mutation/semantic-mutation-runtime.js +521 -0
  342. package/dist/mutation/semantic-planner-retry.js +26 -0
  343. package/dist/mutation/semantic-program-roots.js +69 -0
  344. package/dist/mutation/semantic-rename-commonjs.js +229 -0
  345. package/dist/mutation/semantic-rename-config-worker-child.js +46 -0
  346. package/dist/mutation/semantic-rename-config-worker.js +498 -0
  347. package/dist/mutation/semantic-rename-locations.js +192 -0
  348. package/dist/mutation/semantic-rename-model.js +2 -0
  349. package/dist/mutation/semantic-rename-process.js +217 -0
  350. package/dist/mutation/semantic-rename-standalone-engine.js +302 -0
  351. package/dist/mutation/semantic-rename-standalone-planner.js +567 -0
  352. package/dist/mutation/semantic-rename-transaction.js +333 -0
  353. package/dist/mutation/semantic-unused-import-cleanup.js +248 -0
  354. package/dist/mutation/semantic-worker-retry.js +40 -0
  355. package/dist/mutation/semantic-workspace.js +804 -0
  356. package/dist/mutation/targeted-import-canonicalizer.js +359 -0
  357. package/dist/observability/config.js +206 -1
  358. package/dist/observability/context.js +59 -1
  359. package/dist/observability/failure-snapshot.js +124 -2
  360. package/dist/observability/recent.js +63 -2
  361. package/dist/payloads/read-stdin-json.js +212 -1
  362. package/dist/rg-wrapper/core.js +714 -6
  363. package/dist/rg-wrapper/options.js +125 -1
  364. package/dist/rtk-wrapper/core.js +144 -2
  365. package/dist/rtk-wrapper/git-safety.js +203 -0
  366. package/dist/rtk-wrapper/output-adapter.js +106 -0
  367. package/dist/runtime/buffered-process.js +114 -0
  368. package/dist/runtime/bundled-node.js +97 -1
  369. package/dist/runtime/command-lifecycle.js +2 -0
  370. package/dist/runtime/input-source.js +238 -1
  371. package/dist/runtime/node-cli-identity.js +37 -0
  372. package/dist/runtime/run-command.js +191 -1
  373. package/dist/selectors/parse-entities.js +84 -1
  374. package/dist/semantic/semantic-context-pool.js +830 -0
  375. package/dist/semantic/semantic-context-provider.js +416 -0
  376. package/dist/semantic/semantic-resident-admission.js +38 -0
  377. package/dist/semantic/semantic-worker-child.js +40 -0
  378. package/dist/semantic/semantic-worker-manager.js +460 -0
  379. package/dist/semantic/semantic-worker-protocol.js +2 -0
  380. package/dist/semantic/semantic-worker-runtime.js +38 -0
  381. package/dist/semantic/workspace-semantic-context-pools.js +136 -0
  382. package/dist/session/client.js +359 -1
  383. package/dist/session/daemon-state.js +185 -2
  384. package/dist/session/external-tool-coordinator.js +88 -0
  385. package/dist/session/external-tool-request.js +52 -0
  386. package/dist/session/lane-owner.js +116 -0
  387. package/dist/session/paths.js +71 -1
  388. package/dist/session/runtime-lifecycle.js +225 -0
  389. package/dist/session/runtime-shutdown.js +95 -0
  390. package/dist/session/server.js +1194 -7
  391. package/dist/session/session-health.js +27 -0
  392. package/dist/shared/agent-text.js +29 -1
  393. package/dist/shared/errors.js +496 -30
  394. package/dist/shared/event-loop.js +6 -1
  395. package/dist/shared/hints.js +37 -1
  396. package/dist/shared/metrics.js +43 -1
  397. package/dist/shared/presentation.js +69 -4
  398. package/dist/shared/stdin-examples.js +77 -1
  399. package/dist/shared/stdout.js +6 -2
  400. package/dist/shared/types.js +23 -1
  401. package/dist/tool-runtime/runtime-tools.js +120 -1
  402. package/dist/topology/availability.js +663 -0
  403. package/dist/topology/cache.js +130 -0
  404. package/dist/topology/candidates.js +372 -0
  405. package/dist/topology/core.js +903 -0
  406. package/dist/topology/dependency-snapshot.js +189 -0
  407. package/dist/topology/model.js +2 -0
  408. package/dist/topology/scope.js +100 -0
  409. package/dist/topology/ts-oracle-batch.js +529 -0
  410. package/dist/topology/ts-oracle-host.js +69 -0
  411. package/dist/topology/ts-oracle-model.js +2 -0
  412. package/dist/topology/ts-oracle.js +224 -0
  413. package/dist/topology/tsconfig-loader.js +105 -0
  414. package/dist/topology/workspace-project-index.js +542 -0
  415. package/dist/tracing/config.js +192 -2
  416. package/dist/tracing/failure-summary.js +100 -0
  417. package/dist/tracing/trace.js +318 -5
  418. package/dist/tsc-wrapper/core.js +697 -0
  419. package/dist/workers/control-plane/aib-control-plane-worker.cjs +32 -32
  420. package/dist/workers/control-plane/client-config.default.json +3 -3
  421. package/dist/workers/lexical-worker-child.js +27 -0
  422. package/dist/workers/lexical-worker-manager.js +394 -0
  423. package/dist/workers/lexical-worker-protocol.js +2 -0
  424. package/dist/workers/lexical-worker-runtime.js +25 -0
  425. package/dist/workers/owned-one-shot-process.js +115 -0
  426. package/dist/workers/product-storage.js +23 -1
  427. package/dist/workers/registry.js +241 -1
  428. package/package.json +8 -13
  429. package/scripts/postinstall.cjs +29 -29
  430. package/scripts/provision-runtime.cjs +411 -459
  431. package/dist/client/http-client.js +0 -1
  432. package/dist/client/transport-options.js +0 -1
  433. package/dist/client/websocket-client.js +0 -1
  434. package/dist/commands/entity-resolution.js +0 -1
  435. package/dist/commands/file-command.js +0 -1
  436. package/dist/commands/host-command.js +0 -1
  437. package/dist/commands/inspect-symbol-query.js +0 -1
  438. package/dist/commands/list-instances.js +0 -1
  439. package/dist/commands/module-plan-command.js +0 -1
  440. package/dist/commands/move-command.js +0 -1
  441. package/dist/commands/move-to-file.js +0 -2
  442. package/dist/commands/ping.js +0 -1
  443. package/dist/commands/refactor-command.js +0 -1
  444. package/dist/commands/rename-command.js +0 -1
  445. package/dist/commands/runtime-command.js +0 -4
  446. package/dist/commands/runtime-info.js +0 -1
  447. package/dist/commands/validate-module-plan.js +0 -2
  448. package/dist/compatibility/policy.js +0 -1
  449. package/dist/config/auto-start-ide.js +0 -1
  450. package/dist/discovery/registry.js +0 -1
  451. package/dist/discovery/select-instance.js +0 -1
  452. package/dist/help/docs/file.rename.md +0 -35
  453. package/dist/help/docs/mutation.md +0 -60
  454. package/dist/help/docs/refactor.batch.md +0 -44
  455. package/dist/help/dsl/docs/file.rename.md +0 -35
  456. package/dist/help/dsl/docs/mutation.md +0 -60
  457. package/dist/help/dsl/docs/refactor.batch.md +0 -44
  458. package/dist/help/dsl/topics/file.rename.md +0 -33
  459. package/dist/help/dsl/topics/mutation.md +0 -58
  460. package/dist/help/dsl/topics/refactor.batch.md +0 -33
  461. package/dist/help/topics/file.rename.md +0 -33
  462. package/dist/help/topics/mutation.md +0 -58
  463. package/dist/help/topics/refactor.batch.md +0 -33
  464. package/dist/ide-launch/common.cjs +0 -162
  465. package/dist/managed-host/extension-vsix-resolver.js +0 -1
  466. package/dist/managed-host/manage-serve-web-host.cjs +0 -141
  467. package/dist/managed-host/serve-web-autostart.js +0 -1
  468. package/dist/managed-host/serve-web-host.cjs +0 -2115
  469. package/dist/runtime/managed-runtime-provisioning.js +0 -1
  470. package/dist/shared/diagnostic-catalog.js +0 -1
  471. package/dist/shared/diagnostics.js +0 -1
  472. package/dist/shared/operations.js +0 -1
  473. package/dist/shared/protocol.js +0 -1
  474. package/dist/shared/routes.js +0 -1
  475. package/extension/vscode-refactor-bridge-extension.vsix +0 -0
  476. package/runtimes/launcher/linux-x64/aib +0 -0
  477. package/runtimes/launcher/win-x64/aib.exe +0 -0
@@ -1,7 +1,1194 @@
1
- "use strict";var re=exports&&exports.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(t,n);(!s||("get"in s?!t.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,s)}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),oe=exports&&exports.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),$=exports&&exports.__importStar||(function(){var e=function(t){return e=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},e(t)};return function(t){if(t&&t.__esModule)return t;var n={};if(t!=null)for(var r=e(t),s=0;s<r.length;s++)r[s]!=="default"&&re(n,t,r[s]);return oe(n,t),n}})();Object.defineProperty(exports,"__esModule",{value:!0}),exports.CliSessionServer=void 0,exports.runSessionServerCli=Be;const D=$(require("node:fs")),se=$(require("node:http")),ie=require("../config/product-storage"),ae=require("../shared/agent-text"),ce=require("../shared/event-loop"),h=require("../shared/errors"),I=require("../shared/metrics"),ue=require("../shared/stdout"),j=require("../shared/presentation"),le=require("../tracing/trace"),A=require("../runtime/run-command"),de=require("../config/resolve-command-alias"),x=require("../config/auto-start-ide"),o=require("../config/env-vars"),me=require("../client/transport-options"),L=require("./paths"),H=require("./daemon-state"),b=require("../commands/module-plan-cache"),fe=require("../commands/execution-command"),O=require("../payloads/read-stdin-json"),F=require("../commands/module-plan-timeout"),S=require("../diagnostics/module-plan-timeline"),U=require("../commands/mutation-execution-cache"),Ie=require("../rg-wrapper/core"),pe=require("../rg-wrapper/options"),w=require("../rtk-wrapper/core"),ge=!1,Se=!1;function he(e){D.mkdirSync((0,L.getSessionDir)(),{recursive:!0}),G((0,L.getSessionInfoPath)(),JSON.stringify(e,null,2)),G((0,L.getSessionUrlPath)(),`${e.url}
2
- `)}function _e(){D.rmSync((0,L.getSessionInfoPath)(),{force:!0}),D.rmSync((0,L.getSessionUrlPath)(),{force:!0})}function G(e,t){const n=`${e}.${process.pid}.tmp`;D.writeFileSync(n,t),D.renameSync(n,e)}async function q(e){const t=[];for await(const n of e)t.push(Buffer.isBuffer(n)?n:Buffer.from(String(n)));return Buffer.concat(t).toString("utf8")}function _(e,t,n){const r=JSON.stringify(n,null,2);e.writeHead(t,{"content-type":"application/json; charset=utf-8","content-length":Buffer.byteLength(r)}),e.end(r)}function ye(e){const t=new Set(["NO_COLOR","CLICOLOR","CLICOLOR_FORCE","TERM","RG_CONFIG_PATH","RIPGREP_CONFIG_PATH","AIB_RG_TRIM_SPACES","AIB_RG_ALIASES",o.CLI_ENV.rgPath,o.CLI_ENV.rtkPath,o.CLI_ENV.productStorageDir,o.CLI_ENV.helpShell]),n={};for(const[r,s]of e.entries()){if(!r.startsWith("env."))continue;const a=r.slice(4);t.has(a)&&(n[a]=s)}return n}function Ee(e){if((0,w.isRtkPassthroughCommand)(e.command))return(0,w.runRtkPassthrough)({tool:e.command,args:e.restArgs,cwd:e.cwd,env:{...process.env,...e.env},...e.stdinText!==void 0?{stdinText:e.stdinText}:{}});if(e.command!=="rg")throw new h.CliError("UNSUPPORTED_EXEC_COMMAND",`Unsupported exec command: ${e.command}`,{supported:["rg --",...w.RTK_PASSTHROUGH_COMMANDS.map(t=>`${t} --`)]});return(0,Ie.runBrgFormatted)({args:e.restArgs,cwd:e.cwd,env:{...process.env,...e.env},...e.stdinText!==void 0?{stdinText:e.stdinText}:{}},(0,pe.resolveBrgFormatOptions)(e.cwd,e.restArgs,{...process.env,...e.env}))}function R(e,t){if(e.destroyed||e.writableEnded)return;e.write(`${JSON.stringify(t)}
3
- `);const n=e;typeof n.flush=="function"&&n.flush()}function Me(e,t,n,r){if(e!==null)return(0,O.parseStdinPayload)(e,{command:t,restArgs:n,...r!==void 0?{format:r}:{}})}function Pe(e,t,n,r){if(e!==null)return(0,O.parseInputPayloadWithSource)(e,{command:t,restArgs:n,...r!==void 0?{format:r}:{}}).source}function Ce(e){if(e==null)return;if(!e||typeof e!="object"||Array.isArray(e))throw new h.CliError("INVALID_SESSION_REQUEST","Invalid stdin input source.");const t=e;if(t.format!=="json"&&t.format!=="dsl"||typeof t.text!="string")throw new h.CliError("INVALID_SESSION_REQUEST","Invalid stdin input source.");return{format:t.format,text:t.text}}function J(e){if(e==null||e==="")return;const t=(0,me.parseExtensionTransport)(e);if(!t)throw new h.CliError("INVALID_TRANSPORT","Expected transport to be either http or websocket.");return t}function ve(e){if(!e||typeof e!="object"||Array.isArray(e))return{};const t=new Set([o.CLI_ENV.managedHostScript,o.CLI_ENV.managedHostKind,o.CLI_ENV.managedHostRunDir,o.CLI_ENV.codeServerPath,o.CLI_ENV.extensionVsix,o.CLI_ENV.ideCommand,o.CLI_ENV.chromePath,o.CLI_ENV.managedHostWaitMs,o.CLI_ENV.workspaceRoot,o.CLI_ENV.helpShell,o.CLI_ENV.disableWatchers,o.CLI_ENV.trace,o.CLI_ENV.traceDir,o.CLI_ENV.failureSnapshots,o.CLI_ENV.productStorageDir,o.CLI_ENV.metrics,o.CLI_ENV.metricsDir,o.CLI_ENV.metricsTag,o.CLI_ENV.mutationImpactMetrics,o.CLI_ENV.mutationImpactStream,o.CLI_ENV.testMoveToFileFailEntity,o.CLI_ENV.testPostMutationCyclesDelayMs,o.CLI_ENV.testRefactorBatchDelayMs,o.CLI_ENV.testRenameDelayMs,o.CLI_ENV.testFileMoveToDirDelayMs,o.CLI_ENV.testFileMoveToDirRowDelayMs,o.CLI_ENV.testFileMoveToDirImportsDelayMs,o.CLI_ENV.testFileMoveToDirFailImports,o.CLI_ENV.testFileRenameDelayMs,o.CLI_ENV.testFileRenameRowDelayMs,o.CLI_ENV.testFileRenameImportsDelayMs,o.CLI_ENV.testFileRenameFailImports,o.CLI_ENV.testFileRefactorBatchDelayMs,o.CLI_ENV.testFileRefactorBatchRowDelayMs,o.CLI_ENV.testFileRefactorBatchImportsDelayMs,o.CLI_ENV.testFileRefactorBatchFailImports,o.CLI_ENV.disableFileMutationImportPostProcess,o.CLI_ENV.disableFileMoveImportPostProcess,o.CLI_ENV.modulePlanSyncWaitMs,o.CLI_ENV.refactorBatchSyncWaitMs,o.CLI_ENV.renameSyncWaitMs,o.CLI_ENV.fileMoveToDirSyncWaitMs,o.CLI_ENV.fileRenameSyncWaitMs,o.CLI_ENV.fileRefactorBatchSyncWaitMs,o.CLI_ENV.modulePlanDebugTimeline]),n={};for(const[r,s]of Object.entries(e))t.has(r)&&typeof s=="string"&&(n[r]=s);return n}async function B(e,t){const n=Object.entries(e);if(n.length===0)return t();const r=new Map;for(const[s,a]of n)r.set(s,process.env[s]),process.env[s]=a;try{return await t()}finally{for(const[s,a]of r)a===void 0?delete process.env[s]:process.env[s]=a}}function K(e,t){e.setHeader("x-aib-execution-mode",t)}async function Q(e,t,n){return(0,S.recordModulePlanTimeline)(e.cwd,e.modulePlanExecutionId,"session.deadline.wait.start",{deadlineMs:n}),(0,U.waitForMutationDeadline)(t.then(r=>((0,S.recordModulePlanTimeline)(e.cwd,e.modulePlanExecutionId,"session.deadline.runPromise.resolved"),r)),n,()=>(0,S.recordModulePlanTimeline)(e.cwd,e.modulePlanExecutionId,"session.deadline.timer.fired",{deadlineMs:n}))}function z(e){if(e.command!=="modulePlan")return 0;const t=e.restArgs[0]??"";return t!=="execute"&&t!=="apply"?0:(0,U.readMutationSyncWaitMs)(process.env[o.CLI_ENV.modulePlanSyncWaitMs],12e4)}async function X(e,t){const n=e.modulePlanExecutionId??"last";await(0,ce.yieldToEventLoop)();let r;try{(0,S.recordModulePlanTimeline)(e.cwd,n,"session.inProgress.status.read.start",{elapsedMs:t}),r=(0,fe.runExecutionCommand)(e.cwd,["status",n]),(0,S.recordModulePlanTimeline)(e.cwd,n,"session.inProgress.status.read.end",{status:typeof r.status=="string"?r.status:null,phase:typeof r.phase=="string"?r.phase:null,summary:typeof r.summary=="string"?r.summary:null})}catch{(0,S.recordModulePlanTimeline)(e.cwd,n,"session.inProgress.status.read.failed",{elapsedMs:t}),r={operation:"execution.status",executionId:n,status:"running",summary:"in progress"}}const s=ne(e),a=s?s.estimatedDurationMs-t:null,i=we(r,e,a);return(0,ae.attachAgentText)({...r,operation:r.operation??"execution.status",executionId:n,status:r.status??"running",...a!==null?{estimatedRemainingMs:Math.max(0,a)}:{}},i)}function we(e,t,n){const r=typeof e.executionId=="string"?e.executionId:t.modulePlanExecutionId??"last",a=[`modulePlan.${t.restArgs[0]??"execute"} ${r}`];return typeof e.summary=="string"&&e.summary.length>0&&a.push(e.summary),e.phase==="preview"&&a.push("previewing plan"),e.phase==="mutation"&&a.push("applying mutation"),e.phase==="postMutation.cycles"&&(a.push("mutation completed"),a.push("checking cycles")),n!==null&&a.push(n>0?`estimated remaining: ${(0,F.formatModulePlanTimeoutEstimate)(Math.max(n,5e3))}`:"estimated remaining: check status again soon"),a.join(`
4
- `)}class Y{server;daemonId=`${process.pid}-${Date.now().toString(36)}`;daemonStartedAt=new Date().toISOString();daemonPackage=(0,H.currentCliDaemonPackage)();runningExecutions=new Map;activeInvokeCount=0;heartbeatTimer=null;constructor(){this.server=se.createServer((t,n)=>{this.handleRequest(t,n)})}async handleRequest(t,n){if(t.method==="GET"&&t.url==="/health"){_(n,200,{ok:!0,pid:process.pid});return}if(t.method==="POST"&&t.url==="/run")try{const r=await q(t),s=r?JSON.parse(r):{};if(typeof s.command!="string"||!Array.isArray(s.restArgs)||typeof s.cwd!="string")throw new h.CliError("INVALID_SESSION_REQUEST","Invalid session request payload.");const a=Ce(s.stdinInputSource),i={command:s.command,restArgs:s.restArgs.filter(f=>typeof f=="string"),cwd:s.cwd,stdinPayload:s.stdinPayload,metricsEnabled:s.metricsEnabled===!0};a!==void 0&&(i.stdinInputSource=a);const c=J(s.transport),u=ve(s.env);c&&(i.transport=c),i.autoStartIde=(0,x.autoStartIdePolicyFromSession)(s.autoStartIde)??(0,x.resolveAutoStartIdePolicy)();const d=i.metricsEnabled?[]:void 0;d&&(i.metricsSpans=d),typeof s.instanceId=="string"&&(i.instanceId=s.instanceId),typeof s.sessionId=="string"&&(i.sessionId=s.sessionId),typeof s.modulePlanExecutionId=="string"&&(i.modulePlanExecutionId=s.modulePlanExecutionId),s.suppressModulePlanStreamStart===!0&&(i.suppressModulePlanStreamStart=!0);const M=(0,I.metricsNow)(),P=this.beginInvocation(i),E=B(u,()=>(0,A.runCommand)(i)).then(f=>((0,I.recordSpan)(d,"session.runCommand",M),f),f=>{throw(0,I.recordSpan)(d,"session.runCommand",M),f}).finally(P),m=z(i);if(m>0){const f=await Q(i,E,m);if(f.status==="deadline"){E.catch(()=>{}),(0,S.recordModulePlanTimeline)(i.cwd,i.modulePlanExecutionId,"session.run.deadline.output.start",{deadlineMs:m});const p=await X(i,m);(0,S.recordModulePlanTimeline)(i.cwd,i.modulePlanExecutionId,"session.run.response.write.start",{mode:"deadline"}),_(n,200,p),(0,S.recordModulePlanTimeline)(i.cwd,i.modulePlanExecutionId,"session.run.response.write.end",{mode:"deadline"});return}const l=f.result;(0,S.recordModulePlanTimeline)(i.cwd,i.modulePlanExecutionId,"session.run.response.write.start",{mode:"result"}),_(n,200,d?(0,I.appendMetrics)(l,d):l),(0,S.recordModulePlanTimeline)(i.cwd,i.modulePlanExecutionId,"session.run.response.write.end",{mode:"result"});return}const C=await E;(0,S.recordModulePlanTimeline)(i.cwd,i.modulePlanExecutionId,"session.run.response.write.start",{mode:"no-deadline"}),_(n,200,d?(0,I.appendMetrics)(C,d):C),(0,S.recordModulePlanTimeline)(i.cwd,i.modulePlanExecutionId,"session.run.response.write.end",{mode:"no-deadline"});return}catch(r){_(n,500,(0,h.errorPayload)(r));return}if(t.method==="POST"&&t.url==="/invoke"){let r=null,s=null,a=0,i=null;try{const c=await q(t);i=await Le(c);const u=ee(i.input);if(K(n,u),u==="process"){const l=this.beginInvocation(i.input),p=Ne(()=>Ee(Te(i)),l);_(n,200,p);return}if(u==="stream"){De(n),a=Date.now(),s=te(i,a),r=Ve(n,i.input);const l=i.env,p=(0,I.metricsNow)(),g=this.beginInvocation(i.input),y=await B(l,()=>(0,A.runCommand)(i.input)).then(V=>((0,I.recordSpan)(i.spans,"session.runCommand",p),V),V=>{throw(0,I.recordSpan)(i.spans,"session.runCommand",p),V}).finally(g),k=T(i.spans?(0,I.appendMetrics)(y,i.spans):y);N(s,i,k,0,a),R(n,{type:"result",payload:k}),n.end();return}a=Date.now(),s=te(i,a);const d=i.env,M=(0,I.metricsNow)(),P=this.beginInvocation(i.input),E=B(d,()=>(0,A.runCommand)(i.input)).then(l=>((0,I.recordSpan)(i.spans,"session.runCommand",M),l),l=>{throw(0,I.recordSpan)(i.spans,"session.runCommand",M),l}).finally(P),m=z(i.input);if(m>0){const l=await Q(i.input,E,m);if(l.status==="deadline"){E.catch(()=>{});const v=T(await X(i.input,m));N(s,i,v,0,a),_(n,200,v);return}const p=l.result,g=T(i.spans?(0,I.appendMetrics)(p,i.spans):p);N(s,i,g,0,a),_(n,200,g);return}const C=await E,f=T(i.spans?(0,I.appendMetrics)(C,i.spans):C);N(s,i,f,0,a),_(n,200,f);return}catch(c){const u=T((0,h.errorPayload)(c));if(!n.headersSent){K(n,"structured"),_(n,500,u);return}if(n.getHeader("x-aib-execution-mode")==="stream"){N(s,i,u,1,a),R(n,{type:"error",payload:u}),n.end();return}N(s,i,u,1,a),_(n,500,u);return}finally{r&&clearInterval(r)}}_(n,404,{ok:!1,error:"Not found"})}async serve(){await new Promise((s,a)=>{this.server.once("error",a),this.server.listen(0,"127.0.0.1",()=>s())});const t=this.server.address();if(!t||typeof t=="string")throw new Error("Failed to determine aib session address.");he({pid:process.pid,host:"127.0.0.1",port:t.port,url:`http://127.0.0.1:${t.port}`,startedAt:new Date().toISOString()}),this.writeDaemonState("running"),this.heartbeatTimer=setInterval(()=>this.writeDaemonState("running"),1e4),this.heartbeatTimer.unref();let n=!1;const r=()=>{n||(n=!0,this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null),this.writeDaemonState("stopped"),_e(),this.server.close(()=>{process.exit(0)}),setTimeout(()=>{process.exit(0)},1e3).unref())};process.on("SIGTERM",r),process.on("SIGINT",r),await new Promise(()=>{})}beginInvocation(t){this.activeInvokeCount+=1;const n=typeof t.modulePlanExecutionId=="string"?t.modulePlanExecutionId:null;n&&this.runningExecutions.set(n,{executionId:n,command:`${t.command} ${t.restArgs.join(" ")}`.trim(),startedAt:new Date().toISOString()}),this.writeDaemonState("running");let r=!1;return()=>{r||(r=!0,this.activeInvokeCount=Math.max(0,this.activeInvokeCount-1),n&&this.runningExecutions.delete(n),this.writeDaemonState("running"))}}writeDaemonState(t){(0,H.writeCliDaemonIdentity)((0,ie.productStorageRoot)(),{schemaVersion:1,daemonId:this.daemonId,pid:process.pid,status:t,startedAt:this.daemonStartedAt,updatedAt:new Date().toISOString(),heartbeatAt:new Date().toISOString(),invokeProtocol:"http-session-v1",supportedModes:["structured","process","stream"],activeInvokeCount:this.activeInvokeCount,runningExecutions:Array.from(this.runningExecutions.values()),cliPath:this.daemonPackage.cliPath,packageRoot:this.daemonPackage.packageRoot})}}exports.CliSessionServer=Y;function Ne(e,t){try{return e()}finally{t()}}function Z(e){return e.command==="diagnostics"&&e.restArgs[0]==="timeout-stream"}function De(e){e.writeHead(200,{"content-type":"application/x-ndjson; charset=utf-8","cache-control":"no-cache","x-accel-buffering":"no"}),e.flushHeaders()}async function Le(e){const t=new URLSearchParams(e);return{...await Re(t,{invokeGate:!0}),params:t}}async function Re(e,t={}){const n=e.get("command")??e.get("method")??"",r=e.get("cwd")??"",s=e.get("instanceId")??void 0,a=e.get("sessionId")??void 0,i=e.get("modulePlanExecutionId")??void 0,c=e.get("suppressModulePlanStreamStart")==="true",u=e.get("metricsEnabled")==="true",d=J(e.get("transport")),M=(0,x.autoStartIdePolicyFromSession)(e.get("autoStartIde"))??(0,x.resolveAutoStartIdePolicy)(),P=Fe(e.get("traceDir")),E=xe(e);if(!n.trim())throw new h.CliError("MISSING_COMMAND","Missing command.");if(!r.trim())throw new h.CliError("MISSING_CWD","Missing cwd.");const m=u?[]:void 0,C=(0,I.metricsNow)(),f=await(0,de.resolveCanonicalCommandAlias)(n.trim(),r,s,M);(0,I.recordSpan)(m,"session.aliasResolution",C);const l=(0,O.stripStdinFormatFlags)(e.getAll("arg")),p=l.restArgs,g={command:f,restArgs:p,cwd:r,metricsEnabled:u,autoStartIde:M};if(d&&(g.transport=d),s&&(g.instanceId=s),a&&(g.sessionId=a),i&&(g.modulePlanExecutionId=i),c&&(g.suppressModulePlanStreamStart=!0),m&&(g.metricsSpans=m),t.streamGate===!0&&!Z(g)||t.invokeGate===!0&&ee(g)==="process")return{input:g,spans:m,...P!==void 0?{traceDir:P}:{},env:E};const v=Pe(e.get("stdin"),f,p,l.format),y={command:f,restArgs:p,cwd:r,stdinPayload:Me(e.get("stdin"),f,p,l.format),metricsEnabled:u,autoStartIde:M};return v!==void 0&&(y.stdinInputSource=v),d&&(y.transport=d),s&&(y.instanceId=s),a&&(y.sessionId=a),i&&(y.modulePlanExecutionId=i),c&&(y.suppressModulePlanStreamStart=!0),m&&(y.metricsSpans=m),{input:y,spans:m,...P!==void 0?{traceDir:P}:{},env:E}}function ee(e){return e.command==="rg"&&e.restArgs[0]==="--"||(0,w.isRtkPassthroughCommand)(e.command)&&e.restArgs[0]==="--"?"process":Z(e)?"stream":"structured"}function Te(e){if(!((e.input.command==="rg"||(0,w.isRtkPassthroughCommand)(e.input.command))&&e.input.restArgs[0]==="--"))throw new h.CliError("UNSUPPORTED_INVOKE_PROCESS_COMMAND",`Unsupported process invocation: ${e.input.command}`,{supported:["rg --",...w.RTK_PASSTHROUGH_COMMANDS.map(r=>`${r} --`)]});const n={command:e.input.command,restArgs:e.input.restArgs.slice(1),cwd:e.input.cwd,env:ye(e.params)};return e.params.has("stdin")&&(n.stdinText=e.params.get("stdin")??""),n}function xe(e){const t={},n=[[o.CLI_ENV.metrics,e.get("metrics")??""],[o.CLI_ENV.metricsDir,e.get("metricsDir")??""],[o.CLI_ENV.metricsTag,e.get("metricsTag")??""],[o.CLI_ENV.mutationImpactMetrics,e.get("mutationImpactMetrics")??""],[o.CLI_ENV.mutationImpactStream,e.get("mutationImpactStream")??""],[o.CLI_ENV.testMoveToFileFailEntity,e.get("testMoveToFileFailEntity")??""],[o.CLI_ENV.testPostMutationCyclesDelayMs,e.get("testPostMutationCyclesDelayMs")??""],[o.CLI_ENV.testRefactorBatchDelayMs,e.get("testRefactorBatchDelayMs")??""],[o.CLI_ENV.testRenameDelayMs,e.get("testRenameDelayMs")??""],[o.CLI_ENV.testFileMoveToDirDelayMs,e.get("testFileMoveToDirDelayMs")??""],[o.CLI_ENV.testFileMoveToDirRowDelayMs,e.get("testFileMoveToDirRowDelayMs")??""],[o.CLI_ENV.testFileMoveToDirImportsDelayMs,e.get("testFileMoveToDirImportsDelayMs")??""],[o.CLI_ENV.testFileMoveToDirFailImports,e.get("testFileMoveToDirFailImports")??""],[o.CLI_ENV.testFileRenameDelayMs,e.get("testFileRenameDelayMs")??""],[o.CLI_ENV.testFileRenameRowDelayMs,e.get("testFileRenameRowDelayMs")??""],[o.CLI_ENV.testFileRenameImportsDelayMs,e.get("testFileRenameImportsDelayMs")??""],[o.CLI_ENV.testFileRenameFailImports,e.get("testFileRenameFailImports")??""],[o.CLI_ENV.testFileRefactorBatchDelayMs,e.get("testFileRefactorBatchDelayMs")??""],[o.CLI_ENV.testFileRefactorBatchRowDelayMs,e.get("testFileRefactorBatchRowDelayMs")??""],[o.CLI_ENV.testFileRefactorBatchImportsDelayMs,e.get("testFileRefactorBatchImportsDelayMs")??""],[o.CLI_ENV.testFileRefactorBatchFailImports,e.get("testFileRefactorBatchFailImports")??""],[o.CLI_ENV.disableFileMutationImportPostProcess,e.get("disableFileMutationImportPostProcess")??""],[o.CLI_ENV.disableFileMoveImportPostProcess,e.get("disableFileMoveImportPostProcess")??""],[o.CLI_ENV.modulePlanSyncWaitMs,e.get("modulePlanSyncWaitMs")??""],[o.CLI_ENV.refactorBatchSyncWaitMs,e.get("refactorBatchSyncWaitMs")??""],[o.CLI_ENV.renameSyncWaitMs,e.get("renameSyncWaitMs")??""],[o.CLI_ENV.fileMoveToDirSyncWaitMs,e.get("fileMoveToDirSyncWaitMs")??""],[o.CLI_ENV.fileRenameSyncWaitMs,e.get("fileRenameSyncWaitMs")??""],[o.CLI_ENV.fileRefactorBatchSyncWaitMs,e.get("fileRefactorBatchSyncWaitMs")??""],[o.CLI_ENV.modulePlanDebugTimeline,e.get("modulePlanDebugTimeline")??""],[o.CLI_ENV.trace,e.get("trace")??""],[o.CLI_ENV.failureSnapshots,e.get("failureSnapshots")??""],[o.CLI_ENV.productStorageDir,e.get("productStorageDir")??""],[o.CLI_ENV.helpShell,e.get(`env.${o.CLI_ENV.helpShell}`)??""]];for(const[r,s]of n){const a=s.trim();a&&(t[r]=a)}return t}function Fe(e){if(e===null)return;const t=e.trim();return t||void 0}function te(e,t){return e.traceDir?(0,le.startTrace)({cwd:e.input.cwd,argv:[e.input.command,...e.input.restArgs],command:e.input.command,restArgs:e.input.restArgs,...e.input.stdinPayload!==void 0?{stdinPayload:e.input.stdinPayload}:{},...e.input.stdinInputSource!==void 0?{stdinSource:e.input.stdinInputSource}:{},traceDir:e.traceDir,startedAtMs:t}):null}function N(e,t,n,r,s){if(!e?.enabled||!t)return;const a=(0,j.createCliPresentationEnvelope)(n);e.complete({output:a.tracePayload,stdoutText:a.text?`${a.text.trimEnd()}
5
- `:`${JSON.stringify(a.tracePayload,null,2)}
6
- `,exitCode:n.ok===!1?1:r,durationMs:Date.now()-s,...t.input.transport?{transport:t.input.transport}:{}})}function T(e){return(0,j.createCliPresentationEnvelope)(e).payload}function Ve(e,t){if(!be(t))return null;const n=t.modulePlanExecutionId??(0,b.buildModulePlanExecutionId)();t.modulePlanExecutionId=n;const r=Date.now(),s=ne(t),a=s?`
7
- estimated: ${(0,F.formatModulePlanTimeoutEstimate)(s.estimatedDurationMs)}`:"";if(t.suppressModulePlanStreamStart||R(e,{type:"start",text:`modulePlan.${t.restArgs[0]??"execute"} ${n}${a}`,data:{operation:`modulePlan.${t.restArgs[0]??"execute"}`,executionId:n,...s?{estimatedTimeoutMs:s.recommendedTimeoutMs,estimatedDurationMs:s.estimatedDurationMs,suggestedFirstCheckMs:s.suggestedFirstCheckMs,rowCount:s.rowCount,symbolCount:s.symbolCount}:{}}}),!Se)return null;let i=r;return setInterval(()=>{try{const c=(0,b.readModulePlanExecutionStatus)(t.cwd,n),u=Date.parse(c.startedAt);if(Number.isFinite(u)&&u+1e3<r){i=W(e,i);return}if(!(c.completedRows>0||c.failedRows>0||c.filesWritten.length>0)){i=W(e,i);return}R(e,{type:"progress",text:`progress: ${c.completedRows}/${c.rowCount} rows${Ae(c.completedEntities,c.entityCount)}, ${c.filesWritten.length} files`,data:{operation:c.operation,executionId:c.executionId,status:c.status,completedRows:c.completedRows,failedRows:c.failedRows,rowCount:c.rowCount,completedEntities:c.completedEntities,entityCount:c.entityCount,filesWritten:c.filesWritten.length}})}catch{i=W(e,i)}},5e3)}function W(e,t){if(!ge)return t;const n=Date.now();return n-t<3e4?t:(R(e,{type:"progress",text:"modulePlan still running",data:{operation:"modulePlan",status:"running"}}),n)}function Ae(e,t){return!t||t<=0?"":`, ${Math.floor((e??0)/t*100)}% entities`}function be(e){if(e.command!=="modulePlan")return!1;const t=e.restArgs[0]??"";return t==="execute"||t==="apply"}function ne(e){const t=e.restArgs[0]??"";if(t==="execute")return(0,F.estimateModulePlanTimeoutFromRequest)(e.stdinPayload);if(t!=="apply")return null;const n=Oe(e.restArgs);if(!n)return null;try{return(0,F.estimateModulePlanTimeoutFromRequest)((0,b.readModulePlanRecord)(e.cwd,n).normalizedRequest)}catch{return null}}function Oe(e){const t=e.indexOf("--plan");if(t>=0){const r=e[t+1];return r&&!r.startsWith("--")?r:null}return e.slice(1).find(r=>!r.startsWith("--"))??null}async function Be(){const e=process.argv[3]||"status";if(e!=="serve"){(0,ue.printJson)((0,h.errorPayload)(new h.CliError("UNKNOWN_SESSION_COMMAND",`Unknown aib session command: ${e}`))),process.exitCode=1;return}await new Y().serve()}
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.CliSessionServer = void 0;
37
+ exports.runSessionServerCli = runSessionServerCli;
38
+ const fs = __importStar(require("node:fs"));
39
+ const http = __importStar(require("node:http"));
40
+ const product_storage_1 = require("../config/product-storage");
41
+ const request_routing_context_1 = require("../config/request-routing-context");
42
+ const workspace_root_1 = require("../config/workspace-root");
43
+ const agent_text_1 = require("../shared/agent-text");
44
+ const event_loop_1 = require("../shared/event-loop");
45
+ const errors_1 = require("../shared/errors");
46
+ const metrics_1 = require("../shared/metrics");
47
+ const stdout_1 = require("../shared/stdout");
48
+ const presentation_1 = require("../shared/presentation");
49
+ const trace_1 = require("../tracing/trace");
50
+ const run_command_1 = require("../runtime/run-command");
51
+ const resolve_command_alias_1 = require("../config/resolve-command-alias");
52
+ const env_vars_1 = require("../config/env-vars");
53
+ const paths_1 = require("./paths");
54
+ const lane_owner_1 = require("./lane-owner");
55
+ const daemon_state_1 = require("./daemon-state");
56
+ const module_plan_cache_1 = require("../commands/module-plan-cache");
57
+ const execution_command_1 = require("../commands/execution-command");
58
+ const read_stdin_json_1 = require("../payloads/read-stdin-json");
59
+ const module_plan_timeout_1 = require("../commands/module-plan-timeout");
60
+ const module_plan_timeline_1 = require("../diagnostics/module-plan-timeline");
61
+ const mutation_execution_cache_1 = require("../commands/mutation-execution-cache");
62
+ const mutation_eta_1 = require("../commands/mutation-eta");
63
+ const core_1 = require("../rtk-wrapper/core");
64
+ const workspace_semantic_context_pools_1 = require("../semantic/workspace-semantic-context-pools");
65
+ const semantic_worker_manager_1 = require("../semantic/semantic-worker-manager");
66
+ const lexical_worker_manager_1 = require("../workers/lexical-worker-manager");
67
+ const external_tool_coordinator_1 = require("./external-tool-coordinator");
68
+ const runtime_lifecycle_1 = require("./runtime-lifecycle");
69
+ const runtime_shutdown_1 = require("./runtime-shutdown");
70
+ const session_health_1 = require("./session-health");
71
+ const external_tool_request_1 = require("./external-tool-request");
72
+ const MODULE_PLAN_HEARTBEAT_ENABLED = false;
73
+ const MODULE_PLAN_PROGRESS_STREAM_ENABLED = false;
74
+ function writeSessionInfo(info) {
75
+ fs.mkdirSync((0, paths_1.getSessionDir)(), { recursive: true });
76
+ atomicWriteText((0, paths_1.getSessionInfoPath)(), JSON.stringify(info, null, 2));
77
+ atomicWriteText((0, paths_1.getSessionUrlPath)(), `${info.url}\n`);
78
+ }
79
+ function removeSessionInfo(ownerPid = process.pid) {
80
+ try {
81
+ const parsed = JSON.parse(fs.readFileSync((0, paths_1.getSessionInfoPath)(), "utf8"));
82
+ if (parsed.pid !== ownerPid)
83
+ return;
84
+ }
85
+ catch {
86
+ return;
87
+ }
88
+ fs.rmSync((0, paths_1.getSessionInfoPath)(), { force: true });
89
+ fs.rmSync((0, paths_1.getSessionUrlPath)(), { force: true });
90
+ }
91
+ function atomicWriteText(filePath, text) {
92
+ const tmpPath = `${filePath}.${process.pid}.tmp`;
93
+ fs.writeFileSync(tmpPath, text);
94
+ fs.renameSync(tmpPath, filePath);
95
+ }
96
+ async function collectRequestBody(request) {
97
+ const chunks = [];
98
+ for await (const chunk of request) {
99
+ chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk)));
100
+ }
101
+ return Buffer.concat(chunks).toString("utf8");
102
+ }
103
+ function writeJson(response, statusCode, payload) {
104
+ const body = JSON.stringify(payload, null, 2);
105
+ response.writeHead(statusCode, {
106
+ "content-type": "application/json; charset=utf-8",
107
+ "content-length": Buffer.byteLength(body)
108
+ });
109
+ response.end(body);
110
+ }
111
+ function parseExecEnv(params) {
112
+ const allowed = new Set([
113
+ "NO_COLOR",
114
+ "CLICOLOR",
115
+ "CLICOLOR_FORCE",
116
+ "TERM",
117
+ "RG_CONFIG_PATH",
118
+ "RIPGREP_CONFIG_PATH",
119
+ "AIB_RG_TRIM_SPACES",
120
+ "AIB_RG_ALIASES",
121
+ env_vars_1.CLI_ENV.rgPath,
122
+ env_vars_1.CLI_ENV.rtkPath,
123
+ env_vars_1.CLI_ENV.tscPath,
124
+ env_vars_1.CLI_ENV.workspaceRoot,
125
+ env_vars_1.CLI_ENV.productStorageDir,
126
+ env_vars_1.CLI_ENV.helpShell
127
+ ]);
128
+ const env = {};
129
+ for (const [key, value] of params.entries()) {
130
+ if (!key.startsWith("env.")) {
131
+ continue;
132
+ }
133
+ const envName = key.slice("env.".length);
134
+ if (allowed.has(envName)) {
135
+ env[envName] = value;
136
+ }
137
+ }
138
+ return env;
139
+ }
140
+ function writeStreamEvent(response, event) {
141
+ if (response.destroyed || response.writableEnded) {
142
+ return;
143
+ }
144
+ response.write(`${JSON.stringify(event)}\n`);
145
+ const flushable = response;
146
+ if (typeof flushable.flush === "function") {
147
+ flushable.flush();
148
+ }
149
+ }
150
+ function parseCliStdinPayload(rawValue, command, restArgs, format) {
151
+ if (rawValue === null) {
152
+ return undefined;
153
+ }
154
+ return (0, read_stdin_json_1.parseStdinPayload)(rawValue, {
155
+ command,
156
+ restArgs,
157
+ ...(format !== undefined ? { format } : {})
158
+ });
159
+ }
160
+ function parseCliStdinInputSource(rawValue, command, restArgs, format) {
161
+ if (rawValue === null) {
162
+ return undefined;
163
+ }
164
+ return (0, read_stdin_json_1.parseInputPayloadWithSource)(rawValue, {
165
+ command,
166
+ restArgs,
167
+ ...(format !== undefined ? { format } : {})
168
+ }).source;
169
+ }
170
+ function parseSessionInputSource(rawValue) {
171
+ if (rawValue === undefined || rawValue === null) {
172
+ return undefined;
173
+ }
174
+ if (!rawValue || typeof rawValue !== "object" || Array.isArray(rawValue)) {
175
+ throw new errors_1.CliError("INVALID_SESSION_REQUEST", "Invalid stdin input source.");
176
+ }
177
+ const source = rawValue;
178
+ if ((source.format !== "json" && source.format !== "dsl") || typeof source.text !== "string") {
179
+ throw new errors_1.CliError("INVALID_SESSION_REQUEST", "Invalid stdin input source.");
180
+ }
181
+ return {
182
+ format: source.format,
183
+ text: source.text
184
+ };
185
+ }
186
+ function parseSessionEnv(rawValue) {
187
+ if (!rawValue || typeof rawValue !== "object" || Array.isArray(rawValue)) {
188
+ return {};
189
+ }
190
+ const allowed = new Set([
191
+ env_vars_1.CLI_ENV.workspaceRoot,
192
+ env_vars_1.CLI_ENV.helpShell,
193
+ env_vars_1.CLI_ENV.disableWatchers,
194
+ env_vars_1.CLI_ENV.trace,
195
+ env_vars_1.CLI_ENV.traceDir,
196
+ env_vars_1.CLI_ENV.failureSnapshots,
197
+ env_vars_1.CLI_ENV.productStorageDir,
198
+ env_vars_1.CLI_ENV.metrics,
199
+ env_vars_1.CLI_ENV.metricsDir,
200
+ env_vars_1.CLI_ENV.metricsTag,
201
+ env_vars_1.CLI_ENV.mutationImpactMetrics,
202
+ env_vars_1.CLI_ENV.mutationImpactStream,
203
+ env_vars_1.CLI_ENV.testMoveToFileFailEntity,
204
+ env_vars_1.CLI_ENV.testPostMutationCyclesDelayMs,
205
+ env_vars_1.CLI_ENV.testRefactorBatchDelayMs,
206
+ env_vars_1.CLI_ENV.testRenameDelayMs,
207
+ env_vars_1.CLI_ENV.testFileMoveToDirDelayMs,
208
+ env_vars_1.CLI_ENV.testFileMoveToDirRowDelayMs,
209
+ env_vars_1.CLI_ENV.testFileMoveToDirImportsDelayMs,
210
+ env_vars_1.CLI_ENV.testFileMoveToDirFailImports,
211
+ env_vars_1.CLI_ENV.testFileRenameDelayMs,
212
+ env_vars_1.CLI_ENV.testFileRenameRowDelayMs,
213
+ env_vars_1.CLI_ENV.testFileRenameImportsDelayMs,
214
+ env_vars_1.CLI_ENV.testFileRenameFailImports,
215
+ env_vars_1.CLI_ENV.testFileRefactorBatchDelayMs,
216
+ env_vars_1.CLI_ENV.testFileRefactorBatchRowDelayMs,
217
+ env_vars_1.CLI_ENV.testFileRefactorBatchImportsDelayMs,
218
+ env_vars_1.CLI_ENV.testFileRefactorBatchFailImports,
219
+ env_vars_1.CLI_ENV.testFileRefactorBatchCrashAfterFsMove,
220
+ env_vars_1.CLI_ENV.testMutateDelayMs,
221
+ env_vars_1.CLI_ENV.testInspectWorkerFailure,
222
+ env_vars_1.CLI_ENV.disableFileMutationImportPostProcess,
223
+ env_vars_1.CLI_ENV.disableFileMoveImportPostProcess,
224
+ env_vars_1.CLI_ENV.modulePlanSyncWaitMs,
225
+ env_vars_1.CLI_ENV.refactorBatchSyncWaitMs,
226
+ env_vars_1.CLI_ENV.renameSyncWaitMs,
227
+ env_vars_1.CLI_ENV.fileMoveToDirSyncWaitMs,
228
+ env_vars_1.CLI_ENV.fileRenameSyncWaitMs,
229
+ env_vars_1.CLI_ENV.fileRefactorBatchSyncWaitMs,
230
+ env_vars_1.CLI_ENV.mutateSyncWaitMs,
231
+ env_vars_1.CLI_ENV.modulePlanDebugTimeline,
232
+ env_vars_1.CLI_ENV.debugWorkspaceContext
233
+ ]);
234
+ const env = {};
235
+ for (const [key, value] of Object.entries(rawValue)) {
236
+ if (allowed.has(key) && typeof value === "string") {
237
+ env[key] = value;
238
+ }
239
+ }
240
+ return env;
241
+ }
242
+ async function withLegacySessionEnv(env, fn) {
243
+ const entries = Object.entries(env);
244
+ if (entries.length === 0) {
245
+ return fn();
246
+ }
247
+ const previous = new Map();
248
+ for (const [key, value] of entries) {
249
+ previous.set(key, process.env[key]);
250
+ process.env[key] = value;
251
+ }
252
+ try {
253
+ return await fn();
254
+ }
255
+ finally {
256
+ for (const [key, value] of previous) {
257
+ if (value === undefined) {
258
+ delete process.env[key];
259
+ }
260
+ else {
261
+ process.env[key] = value;
262
+ }
263
+ }
264
+ }
265
+ }
266
+ async function withSessionRequestContext(cwd, env, fn) {
267
+ const legacyEnv = { ...env };
268
+ delete legacyEnv[env_vars_1.CLI_ENV.workspaceRoot];
269
+ delete legacyEnv[env_vars_1.CLI_ENV.productStorageDir];
270
+ return (0, request_routing_context_1.runWithRequestRoutingContext)(cwd, env, () => withLegacySessionEnv(legacyEnv, fn));
271
+ }
272
+ function writeInvokeModeHeader(response, mode) {
273
+ response.setHeader("x-aib-execution-mode", mode);
274
+ }
275
+ async function waitForSessionMutationDeadline(input, runPromise, deadlineMs) {
276
+ (0, module_plan_timeline_1.recordModulePlanTimeline)(input.cwd, input.modulePlanExecutionId, "session.deadline.wait.start", { deadlineMs });
277
+ return (0, mutation_execution_cache_1.waitForMutationDeadline)(runPromise.then((result) => {
278
+ (0, module_plan_timeline_1.recordModulePlanTimeline)(input.cwd, input.modulePlanExecutionId, "session.deadline.runPromise.resolved");
279
+ return result;
280
+ }), deadlineMs, () => (0, module_plan_timeline_1.recordModulePlanTimeline)(input.cwd, input.modulePlanExecutionId, "session.deadline.timer.fired", { deadlineMs }));
281
+ }
282
+ function readSessionMutationSyncWaitMs(input) {
283
+ if (!isSessionModulePlanMutation(input)) {
284
+ return 0;
285
+ }
286
+ return (0, mutation_execution_cache_1.readMutationSyncWaitMs)(process.env[env_vars_1.CLI_ENV.modulePlanSyncWaitMs], 120_000);
287
+ }
288
+ async function buildModulePlanInProgressOutput(input, elapsedMs) {
289
+ const executionId = input.modulePlanExecutionId ?? "last";
290
+ await (0, event_loop_1.yieldToEventLoop)();
291
+ let output;
292
+ try {
293
+ (0, module_plan_timeline_1.recordModulePlanTimeline)(input.cwd, executionId, "session.inProgress.status.read.start", { elapsedMs });
294
+ output = (0, execution_command_1.runExecutionCommand)(input.cwd, ["status", executionId]);
295
+ (0, module_plan_timeline_1.recordModulePlanTimeline)(input.cwd, executionId, "session.inProgress.status.read.end", {
296
+ status: typeof output.status === "string" ? output.status : null,
297
+ phase: typeof output.phase === "string" ? output.phase : null,
298
+ summary: typeof output.summary === "string" ? output.summary : null
299
+ });
300
+ }
301
+ catch {
302
+ (0, module_plan_timeline_1.recordModulePlanTimeline)(input.cwd, executionId, "session.inProgress.status.read.failed", { elapsedMs });
303
+ output = {
304
+ operation: "execution.status",
305
+ executionId,
306
+ status: "running",
307
+ summary: "in progress"
308
+ };
309
+ }
310
+ const estimate = estimateModulePlanTimeoutForStream(input);
311
+ const estimatedRemainingMs = estimate
312
+ ? estimate.estimatedDurationMs - elapsedMs
313
+ : null;
314
+ const eta = estimatedRemainingMs !== null
315
+ ? (0, mutation_eta_1.buildMutationEtaHint)(executionId, estimatedRemainingMs)
316
+ : null;
317
+ const text = formatModulePlanInProgressText(output, input, eta);
318
+ return (0, agent_text_1.attachAgentText)({
319
+ ...output,
320
+ operation: output.operation ?? "execution.status",
321
+ executionId,
322
+ status: output.status ?? "running",
323
+ ...(eta ? {
324
+ estimatedRemainingMs: eta.estimatedRemainingMs,
325
+ suggestedFirstCheckMs: eta.suggestedFirstCheckMs,
326
+ next: eta.next
327
+ } : {})
328
+ }, text);
329
+ }
330
+ function formatModulePlanInProgressText(output, input, eta) {
331
+ const executionId = typeof output.executionId === "string"
332
+ ? output.executionId
333
+ : input.modulePlanExecutionId ?? "last";
334
+ const action = input.restArgs[0] ?? "execute";
335
+ const operation = input.command === "mutate" ? "mutate" : "modulePlan";
336
+ const lines = [
337
+ `${operation}.${action} ${executionId}`
338
+ ];
339
+ if (typeof output.summary === "string" && output.summary.length > 0) {
340
+ lines.push(output.summary);
341
+ }
342
+ if (output.phase === "preview") {
343
+ lines.push("previewing plan");
344
+ }
345
+ if (output.phase === "mutation") {
346
+ lines.push("applying mutation");
347
+ }
348
+ if (output.phase === "postMutation.cycles") {
349
+ lines.push("mutation completed");
350
+ lines.push("checking cycles");
351
+ }
352
+ if (eta) {
353
+ lines.push(...(0, mutation_eta_1.formatMutationEtaLines)(eta));
354
+ }
355
+ return lines.join("\n");
356
+ }
357
+ class CliSessionServer {
358
+ server;
359
+ daemonId = `${process.pid}-${Date.now().toString(36)}`;
360
+ daemonStartedAt = new Date().toISOString();
361
+ daemonPackage = (0, daemon_state_1.currentCliDaemonPackage)();
362
+ runningExecutions = new Map();
363
+ semanticContextPools = new workspace_semantic_context_pools_1.WorkspaceSemanticContextPools();
364
+ semanticWorker;
365
+ lexicalWorker;
366
+ externalTools = new external_tool_coordinator_1.ExternalToolCoordinator({ timeoutMs: readExternalToolTimeoutMs() });
367
+ runtimeLifecycle;
368
+ drainTimeoutMs = (0, runtime_lifecycle_1.readSessionDrainTimeoutMs)();
369
+ activeInvokeCount = 0;
370
+ heartbeatTimer = null;
371
+ shutdownPromise = null;
372
+ laneLease = null;
373
+ stoppedPromise;
374
+ resolveStopped;
375
+ constructor() {
376
+ this.stoppedPromise = new Promise((resolve) => { this.resolveStopped = resolve; });
377
+ const semanticWorkerMode = (0, semantic_worker_manager_1.readSemanticWorkerSessionMode)();
378
+ this.semanticWorker = semanticWorkerMode === "off"
379
+ ? null
380
+ : new semantic_worker_manager_1.SemanticWorkerManager({ executionMode: semanticWorkerMode, deadlineMs: (0, semantic_worker_manager_1.readSemanticWorkerDeadlineMs)() });
381
+ const lexicalWorkerMode = (0, lexical_worker_manager_1.readLexicalWorkerSessionMode)();
382
+ this.lexicalWorker = lexicalWorkerMode === "off"
383
+ ? null
384
+ : new lexical_worker_manager_1.LexicalWorkerManager({ mode: lexicalWorkerMode, deadlineMs: (0, lexical_worker_manager_1.readLexicalWorkerDeadlineMs)() });
385
+ this.runtimeLifecycle = new runtime_lifecycle_1.SessionRuntimeLifecycle({
386
+ idleTtlMs: (0, runtime_lifecycle_1.readSessionIdleTtlMs)(),
387
+ onIdle: () => this.shutdown("idle-ttl"),
388
+ externalRetainers: () => this.ownedResourceRetainers()
389
+ });
390
+ this.server = http.createServer((request, response) => {
391
+ if (request.method === "GET" && request.url === "/health") {
392
+ void this.handleRequest(request, response);
393
+ return;
394
+ }
395
+ let finishRequest = null;
396
+ try {
397
+ finishRequest = this.runtimeLifecycle.beginRequest();
398
+ }
399
+ catch (error) {
400
+ writeJson(response, 503, (0, errors_1.errorPayload)(error));
401
+ return;
402
+ }
403
+ void (0, runtime_lifecycle_1.runWithSessionRuntimeLifecycle)(this.runtimeLifecycle, () => this.handleRequest(request, response))
404
+ .finally(() => finishRequest?.());
405
+ });
406
+ }
407
+ async handleRequest(request, response) {
408
+ if (request.method === "GET" && request.url === "/health") {
409
+ writeJson(response, 200, (0, session_health_1.buildSessionHealthPayload)(process.pid, this.runtimeLifecycle.state));
410
+ return;
411
+ }
412
+ if (request.method === "POST" && request.url === "/shutdown") {
413
+ writeJson(response, 202, {
414
+ ok: true,
415
+ accepted: true,
416
+ pid: process.pid
417
+ });
418
+ setImmediate(() => { void this.shutdown("session-stop"); });
419
+ return;
420
+ }
421
+ if (request.method === "POST" && request.url === "/run") {
422
+ try {
423
+ const rawBody = await collectRequestBody(request);
424
+ const parsed = rawBody ? JSON.parse(rawBody) : {};
425
+ if (typeof parsed.command !== "string" ||
426
+ !Array.isArray(parsed.restArgs) ||
427
+ typeof parsed.cwd !== "string") {
428
+ throw new errors_1.CliError("INVALID_SESSION_REQUEST", "Invalid session request payload.");
429
+ }
430
+ const stdinInputSource = parseSessionInputSource(parsed.stdinInputSource);
431
+ const runCommandInput = {
432
+ command: parsed.command,
433
+ restArgs: parsed.restArgs.filter((item) => typeof item === "string"),
434
+ cwd: parsed.cwd,
435
+ stdinPayload: parsed.stdinPayload,
436
+ metricsEnabled: parsed.metricsEnabled === true
437
+ };
438
+ runCommandInput.lifecycle = this.lifecycleServices();
439
+ if (stdinInputSource !== undefined) {
440
+ runCommandInput.stdinInputSource = stdinInputSource;
441
+ }
442
+ const sessionEnv = parseSessionEnv(parsed.env);
443
+ const spans = runCommandInput.metricsEnabled ? [] : undefined;
444
+ if (spans) {
445
+ runCommandInput.metricsSpans = spans;
446
+ }
447
+ if (typeof parsed.sessionId === "string") {
448
+ runCommandInput.sessionId = parsed.sessionId;
449
+ }
450
+ if (typeof parsed.modulePlanExecutionId === "string") {
451
+ runCommandInput.modulePlanExecutionId = parsed.modulePlanExecutionId;
452
+ }
453
+ if (parsed.suppressModulePlanStreamStart === true) {
454
+ runCommandInput.suppressModulePlanStreamStart = true;
455
+ }
456
+ if (parsed.debugWorkspaceContext === true) {
457
+ runCommandInput.debugWorkspaceContext = true;
458
+ }
459
+ ensureSessionModulePlanExecutionId(runCommandInput);
460
+ const runStartedAt = (0, metrics_1.metricsNow)();
461
+ const finishInvocation = this.beginInvocation(runCommandInput);
462
+ const runPromise = withSessionRequestContext(runCommandInput.cwd, sessionEnv, () => (0, run_command_1.runCommand)(runCommandInput)).then((result) => {
463
+ (0, metrics_1.recordSpan)(spans, "session.runCommand", runStartedAt);
464
+ return result;
465
+ }, (error) => {
466
+ (0, metrics_1.recordSpan)(spans, "session.runCommand", runStartedAt);
467
+ throw error;
468
+ }).finally(finishInvocation);
469
+ const deadlineMs = readSessionMutationSyncWaitMs(runCommandInput);
470
+ if (deadlineMs > 0) {
471
+ const deadlineResult = await waitForSessionMutationDeadline(runCommandInput, runPromise, deadlineMs);
472
+ if (deadlineResult.status === "deadline") {
473
+ runPromise.catch(() => undefined);
474
+ (0, module_plan_timeline_1.recordModulePlanTimeline)(runCommandInput.cwd, runCommandInput.modulePlanExecutionId, "session.run.deadline.output.start", { deadlineMs });
475
+ const output = await buildModulePlanInProgressOutput(runCommandInput, deadlineMs);
476
+ (0, module_plan_timeline_1.recordModulePlanTimeline)(runCommandInput.cwd, runCommandInput.modulePlanExecutionId, "session.run.response.write.start", { mode: "deadline" });
477
+ writeJson(response, 200, output);
478
+ (0, module_plan_timeline_1.recordModulePlanTimeline)(runCommandInput.cwd, runCommandInput.modulePlanExecutionId, "session.run.response.write.end", { mode: "deadline" });
479
+ return;
480
+ }
481
+ const result = deadlineResult.result;
482
+ (0, module_plan_timeline_1.recordModulePlanTimeline)(runCommandInput.cwd, runCommandInput.modulePlanExecutionId, "session.run.response.write.start", { mode: "result" });
483
+ writeJson(response, 200, spans ? (0, metrics_1.appendMetrics)(result, spans) : result);
484
+ (0, module_plan_timeline_1.recordModulePlanTimeline)(runCommandInput.cwd, runCommandInput.modulePlanExecutionId, "session.run.response.write.end", { mode: "result" });
485
+ return;
486
+ }
487
+ const result = await runPromise;
488
+ (0, module_plan_timeline_1.recordModulePlanTimeline)(runCommandInput.cwd, runCommandInput.modulePlanExecutionId, "session.run.response.write.start", { mode: "no-deadline" });
489
+ writeJson(response, 200, spans ? (0, metrics_1.appendMetrics)(result, spans) : result);
490
+ (0, module_plan_timeline_1.recordModulePlanTimeline)(runCommandInput.cwd, runCommandInput.modulePlanExecutionId, "session.run.response.write.end", { mode: "no-deadline" });
491
+ return;
492
+ }
493
+ catch (error) {
494
+ writeJson(response, 500, (0, errors_1.errorPayload)(error));
495
+ return;
496
+ }
497
+ }
498
+ if (request.method === "POST" && request.url === "/invoke") {
499
+ let progressTimer = null;
500
+ let trace = null;
501
+ let traceStartedAtMs = 0;
502
+ let invokeRequest = null;
503
+ try {
504
+ const rawBody = await collectRequestBody(request);
505
+ const rawParams = new URLSearchParams(rawBody);
506
+ const requestCwd = rawParams.get("cwd") ?? "";
507
+ invokeRequest = await (0, workspace_root_1.runWithWorkspaceRequestContext)(requestCwd, undefined, () => parseInvokeFormRequest(rawBody));
508
+ invokeRequest.input.lifecycle = this.lifecycleServices();
509
+ const mode = classifyInvokeMode(invokeRequest.input);
510
+ writeInvokeModeHeader(response, mode);
511
+ if (mode === "process") {
512
+ const finishInvocation = this.beginInvocation(invokeRequest.input);
513
+ const requestAbort = new AbortController();
514
+ const onResponseClose = () => {
515
+ if (!response.writableEnded)
516
+ requestAbort.abort("client-disconnected");
517
+ };
518
+ response.once("close", onResponseClose);
519
+ try {
520
+ const execRequest = buildExecRequestFromInvoke(invokeRequest);
521
+ (0, external_tool_request_1.assertExternalToolRequestContext)(execRequest);
522
+ const output = await this.externalTools.execute((signal) => (0, external_tool_request_1.runExternalToolRequest)(execRequest, signal), requestAbort.signal);
523
+ writeJson(response, 200, output);
524
+ return;
525
+ }
526
+ finally {
527
+ response.removeListener("close", onResponseClose);
528
+ finishInvocation();
529
+ }
530
+ }
531
+ if (mode === "stream") {
532
+ writeCliStreamHeaders(response);
533
+ traceStartedAtMs = Date.now();
534
+ trace = startCliFormTrace(invokeRequest, traceStartedAtMs);
535
+ progressTimer = startCliProgressStream(response, invokeRequest.input);
536
+ const requestEnv = invokeRequest.env;
537
+ const runStartedAt = (0, metrics_1.metricsNow)();
538
+ const finishInvocation = this.beginInvocation(invokeRequest.input);
539
+ const runPromise = withSessionRequestContext(invokeRequest.input.cwd, requestEnv, () => (0, run_command_1.runCommand)(invokeRequest.input)).then((result) => {
540
+ (0, metrics_1.recordSpan)(invokeRequest.spans, "session.runCommand", runStartedAt);
541
+ return result;
542
+ }, (error) => {
543
+ (0, metrics_1.recordSpan)(invokeRequest.spans, "session.runCommand", runStartedAt);
544
+ throw error;
545
+ }).finally(finishInvocation);
546
+ const result = await runPromise;
547
+ const output = prepareCliPresentationPayload(invokeRequest.spans ? (0, metrics_1.appendMetrics)(result, invokeRequest.spans) : result);
548
+ completeCliFormTrace(trace, invokeRequest, output, 0, traceStartedAtMs);
549
+ writeStreamEvent(response, {
550
+ type: "result",
551
+ payload: output
552
+ });
553
+ response.end();
554
+ return;
555
+ }
556
+ traceStartedAtMs = Date.now();
557
+ trace = startCliFormTrace(invokeRequest, traceStartedAtMs);
558
+ const requestEnv = invokeRequest.env;
559
+ const runStartedAt = (0, metrics_1.metricsNow)();
560
+ const finishInvocation = this.beginInvocation(invokeRequest.input);
561
+ const runPromise = withSessionRequestContext(invokeRequest.input.cwd, requestEnv, () => (0, run_command_1.runCommand)(invokeRequest.input)).then((result) => {
562
+ (0, metrics_1.recordSpan)(invokeRequest.spans, "session.runCommand", runStartedAt);
563
+ return result;
564
+ }, (error) => {
565
+ (0, metrics_1.recordSpan)(invokeRequest.spans, "session.runCommand", runStartedAt);
566
+ throw error;
567
+ }).finally(finishInvocation);
568
+ const deadlineMs = readSessionMutationSyncWaitMs(invokeRequest.input);
569
+ if (deadlineMs > 0) {
570
+ const deadlineResult = await waitForSessionMutationDeadline(invokeRequest.input, runPromise, deadlineMs);
571
+ if (deadlineResult.status === "deadline") {
572
+ runPromise.catch(() => undefined);
573
+ const output = prepareCliPresentationPayload(await buildModulePlanInProgressOutput(invokeRequest.input, deadlineMs));
574
+ completeCliFormTrace(trace, invokeRequest, output, 0, traceStartedAtMs);
575
+ writeJson(response, 200, output);
576
+ return;
577
+ }
578
+ const result = deadlineResult.result;
579
+ const output = prepareCliPresentationPayload(invokeRequest.spans ? (0, metrics_1.appendMetrics)(result, invokeRequest.spans) : result);
580
+ completeCliFormTrace(trace, invokeRequest, output, 0, traceStartedAtMs);
581
+ writeJson(response, 200, output);
582
+ return;
583
+ }
584
+ const result = await runPromise;
585
+ const output = prepareCliPresentationPayload(invokeRequest.spans ? (0, metrics_1.appendMetrics)(result, invokeRequest.spans) : result);
586
+ completeCliFormTrace(trace, invokeRequest, output, 0, traceStartedAtMs);
587
+ writeJson(response, 200, output);
588
+ return;
589
+ }
590
+ catch (error) {
591
+ if (response.destroyed)
592
+ return;
593
+ const output = prepareCliPresentationPayload((0, errors_1.errorPayload)(error));
594
+ if (!response.headersSent) {
595
+ writeInvokeModeHeader(response, "structured");
596
+ writeJson(response, 500, output);
597
+ return;
598
+ }
599
+ if (response.getHeader("x-aib-execution-mode") === "stream") {
600
+ completeCliFormTrace(trace, invokeRequest, output, 1, traceStartedAtMs);
601
+ writeStreamEvent(response, {
602
+ type: "error",
603
+ payload: output
604
+ });
605
+ response.end();
606
+ return;
607
+ }
608
+ completeCliFormTrace(trace, invokeRequest, output, 1, traceStartedAtMs);
609
+ writeJson(response, 500, output);
610
+ return;
611
+ }
612
+ finally {
613
+ if (progressTimer) {
614
+ clearInterval(progressTimer);
615
+ }
616
+ }
617
+ }
618
+ writeJson(response, 404, {
619
+ ok: false,
620
+ error: "Not found"
621
+ });
622
+ }
623
+ async serve() {
624
+ const laneLease = (0, lane_owner_1.acquireSessionLaneLease)(this.daemonPackage.cliPath);
625
+ this.laneLease = laneLease;
626
+ try {
627
+ await new Promise((resolve, reject) => {
628
+ this.server.once("error", reject);
629
+ this.server.listen(0, "127.0.0.1", () => resolve());
630
+ });
631
+ }
632
+ catch (error) {
633
+ laneLease.release();
634
+ throw error;
635
+ }
636
+ const address = this.server.address();
637
+ if (!address || typeof address === "string") {
638
+ laneLease.release();
639
+ this.laneLease = null;
640
+ throw new Error("Failed to determine aib session address.");
641
+ }
642
+ writeSessionInfo({
643
+ pid: process.pid,
644
+ host: "127.0.0.1",
645
+ port: address.port,
646
+ url: `http://127.0.0.1:${address.port}`,
647
+ startedAt: this.daemonStartedAt
648
+ });
649
+ this.writeDaemonState("running");
650
+ this.heartbeatTimer = setInterval(() => this.writeDaemonState("running"), 10_000);
651
+ this.heartbeatTimer.unref();
652
+ this.runtimeLifecycle.start();
653
+ const onSigterm = () => { void this.shutdown("SIGTERM"); };
654
+ const onSigint = () => { void this.shutdown("SIGINT"); };
655
+ process.once("SIGTERM", onSigterm);
656
+ process.once("SIGINT", onSigint);
657
+ await this.stoppedPromise;
658
+ process.removeListener("SIGTERM", onSigterm);
659
+ process.removeListener("SIGINT", onSigint);
660
+ }
661
+ beginInvocation(input) {
662
+ this.activeInvokeCount += 1;
663
+ const executionId = typeof input.modulePlanExecutionId === "string" ? input.modulePlanExecutionId : null;
664
+ if (executionId) {
665
+ this.runningExecutions.set(executionId, {
666
+ executionId,
667
+ command: `${input.command} ${input.restArgs.join(" ")}`.trim(),
668
+ startedAt: new Date().toISOString()
669
+ });
670
+ }
671
+ this.writeDaemonState("running");
672
+ let finished = false;
673
+ return () => {
674
+ if (finished) {
675
+ return;
676
+ }
677
+ finished = true;
678
+ this.activeInvokeCount = Math.max(0, this.activeInvokeCount - 1);
679
+ if (executionId) {
680
+ this.runningExecutions.delete(executionId);
681
+ }
682
+ this.writeDaemonState("running");
683
+ };
684
+ }
685
+ lifecycleServices() {
686
+ return {
687
+ semanticContexts: {
688
+ forWorkspace: (workspaceRoot) => this.semanticContextPools.forWorkspace(workspaceRoot),
689
+ invalidateWorkspace: (workspaceRoot, change) => {
690
+ this.semanticContextPools.invalidateWorkspace(workspaceRoot, change);
691
+ this.semanticWorker?.invalidateWorkspace(workspaceRoot, change);
692
+ }
693
+ },
694
+ ...(this.semanticWorker ? { semanticBoundaries: this.semanticWorker } : {}),
695
+ ...(this.lexicalWorker ? { lexicalGraph: this.lexicalWorker } : {})
696
+ };
697
+ }
698
+ writeDaemonState(status) {
699
+ if (status === "running" && this.runtimeLifecycle.state.phase === "stopped")
700
+ return;
701
+ const runtime = this.runtimeLifecycle.state;
702
+ (0, daemon_state_1.tryWriteCliDaemonIdentity)((0, product_storage_1.productStorageRoot)(), {
703
+ schemaVersion: 1,
704
+ daemonId: this.daemonId,
705
+ pid: process.pid,
706
+ status,
707
+ startedAt: this.daemonStartedAt,
708
+ updatedAt: new Date().toISOString(),
709
+ heartbeatAt: new Date().toISOString(),
710
+ invokeProtocol: "http-session-v1",
711
+ supportedModes: ["structured", "process", "stream"],
712
+ activeInvokeCount: this.activeInvokeCount,
713
+ runningExecutions: Array.from(this.runningExecutions.values()),
714
+ lastActivityAt: runtime.lastActivityAt,
715
+ idleDeadlineAt: runtime.idleDeadlineAt,
716
+ idleTtlMs: runtime.idleTtlMs,
717
+ acceptingRequests: runtime.acceptingRequests,
718
+ idleRetainers: runtime.retainers,
719
+ shutdownReason: runtime.shutdownReason,
720
+ cliPath: this.daemonPackage.cliPath,
721
+ packageRoot: this.daemonPackage.packageRoot
722
+ });
723
+ }
724
+ ownedResourceRetainers() {
725
+ const retainers = [];
726
+ const external = this.externalTools.state;
727
+ if (external.active > 0)
728
+ retainers.push(`external-tools-active:${external.active}`);
729
+ if (external.queued > 0)
730
+ retainers.push(`external-tools-queued:${external.queued}`);
731
+ const semantic = this.semanticWorker?.state;
732
+ if (semantic?.active)
733
+ retainers.push("semantic-worker-active:1");
734
+ if ((semantic?.queued ?? 0) > 0)
735
+ retainers.push(`semantic-worker-queued:${semantic.queued}`);
736
+ const lexical = this.lexicalWorker?.state;
737
+ if (lexical?.active)
738
+ retainers.push("lexical-worker-active:1");
739
+ if ((lexical?.queued ?? 0) > 0)
740
+ retainers.push(`lexical-worker-queued:${lexical.queued}`);
741
+ const semanticLeases = this.semanticContextPools.state.workspaces.reduce((total, workspace) => total + workspace.pool.activeLeases, 0);
742
+ if (semanticLeases > 0)
743
+ retainers.push(`semantic-context-leases:${semanticLeases}`);
744
+ return retainers;
745
+ }
746
+ shutdown(reason) {
747
+ if (this.shutdownPromise)
748
+ return this.shutdownPromise;
749
+ this.runtimeLifecycle.beginShutdown(reason);
750
+ this.writeDaemonState("running");
751
+ const shutdownPromise = (0, runtime_shutdown_1.shutdownSessionRuntime)({
752
+ lifecycle: this.runtimeLifecycle,
753
+ drainTimeoutMs: this.drainTimeoutMs,
754
+ server: this.server,
755
+ shutdownResources: async () => {
756
+ await Promise.allSettled([
757
+ this.semanticWorker?.shutdown() ?? Promise.resolve(),
758
+ this.lexicalWorker?.shutdown() ?? Promise.resolve(),
759
+ this.externalTools.shutdown()
760
+ ]);
761
+ this.semanticContextPools.dispose();
762
+ },
763
+ finalize: () => this.finalizeShutdown(false),
764
+ hardExit: () => this.finalizeShutdown(true)
765
+ }).then(() => undefined);
766
+ this.shutdownPromise = shutdownPromise;
767
+ return shutdownPromise;
768
+ }
769
+ finalizeShutdown(exitProcess) {
770
+ (0, runtime_shutdown_1.finalizeSessionRuntimeBestEffort)([
771
+ () => {
772
+ if (!this.heartbeatTimer)
773
+ return;
774
+ clearInterval(this.heartbeatTimer);
775
+ this.heartbeatTimer = null;
776
+ },
777
+ () => {
778
+ this.runtimeLifecycle.markStopped();
779
+ this.writeDaemonState("stopped");
780
+ },
781
+ () => removeSessionInfo(),
782
+ () => this.laneLease?.release()
783
+ ], () => {
784
+ this.laneLease = null;
785
+ this.resolveStopped();
786
+ if (exitProcess)
787
+ process.exit(0);
788
+ });
789
+ }
790
+ }
791
+ exports.CliSessionServer = CliSessionServer;
792
+ function readExternalToolTimeoutMs() {
793
+ const raw = process.env[env_vars_1.CLI_ENV.externalToolTimeoutMs];
794
+ const parsed = raw ? Number.parseInt(raw, 10) : Number.NaN;
795
+ return Number.isFinite(parsed) && parsed > 0 ? parsed : 30 * 60_000;
796
+ }
797
+ function canRunViaCliStream(input) {
798
+ return input.command === "diagnostics" && input.restArgs[0] === "timeout-stream";
799
+ }
800
+ function writeCliStreamHeaders(response) {
801
+ response.writeHead(200, {
802
+ "content-type": "application/x-ndjson; charset=utf-8",
803
+ "cache-control": "no-cache",
804
+ "x-accel-buffering": "no"
805
+ });
806
+ response.flushHeaders();
807
+ }
808
+ async function parseInvokeFormRequest(rawBody) {
809
+ const params = new URLSearchParams(rawBody);
810
+ return {
811
+ ...await parseCliFormParams(params, { invokeGate: true }),
812
+ params
813
+ };
814
+ }
815
+ async function parseCliFormParams(params, options = {}) {
816
+ const rawCommand = params.get("command") ?? params.get("method") ?? "";
817
+ const cwd = params.get("cwd") ?? "";
818
+ const sessionId = params.get("sessionId") ?? undefined;
819
+ const modulePlanExecutionId = params.get("modulePlanExecutionId") ?? undefined;
820
+ const suppressModulePlanStreamStart = params.get("suppressModulePlanStreamStart") === "true";
821
+ const metricsEnabled = params.get("metricsEnabled") === "true";
822
+ const traceDir = nonEmptyString(params.get("traceDir"));
823
+ const env = parseCliFormEnv(params);
824
+ if (!rawCommand.trim()) {
825
+ throw new errors_1.CliError("MISSING_COMMAND", "Missing command.");
826
+ }
827
+ if (!cwd.trim()) {
828
+ throw new errors_1.CliError("MISSING_CWD", "Missing cwd.");
829
+ }
830
+ const spans = metricsEnabled ? [] : undefined;
831
+ const aliasStartedAt = (0, metrics_1.metricsNow)();
832
+ const command = await (0, resolve_command_alias_1.resolveCanonicalCommandAlias)(rawCommand.trim(), cwd);
833
+ (0, metrics_1.recordSpan)(spans, "session.aliasResolution", aliasStartedAt);
834
+ const stdinFormat = (0, read_stdin_json_1.stripStdinFormatFlags)(params.getAll("arg"));
835
+ const restArgs = stdinFormat.restArgs;
836
+ const preliminaryInput = {
837
+ command,
838
+ restArgs,
839
+ cwd,
840
+ metricsEnabled
841
+ };
842
+ if (sessionId) {
843
+ preliminaryInput.sessionId = sessionId;
844
+ }
845
+ if (modulePlanExecutionId) {
846
+ preliminaryInput.modulePlanExecutionId = modulePlanExecutionId;
847
+ }
848
+ if (suppressModulePlanStreamStart) {
849
+ preliminaryInput.suppressModulePlanStreamStart = true;
850
+ }
851
+ if (spans) {
852
+ preliminaryInput.metricsSpans = spans;
853
+ }
854
+ if ((options.streamGate === true && !canRunViaCliStream(preliminaryInput)) ||
855
+ (options.invokeGate === true && classifyInvokeMode(preliminaryInput) === "process")) {
856
+ return {
857
+ input: preliminaryInput,
858
+ spans,
859
+ ...(traceDir !== undefined ? { traceDir } : {}),
860
+ env
861
+ };
862
+ }
863
+ const stdinInputSource = parseCliStdinInputSource(params.get("stdin"), command, restArgs, stdinFormat.format);
864
+ const input = {
865
+ command,
866
+ restArgs,
867
+ cwd,
868
+ stdinPayload: parseCliStdinPayload(params.get("stdin"), command, restArgs, stdinFormat.format),
869
+ metricsEnabled
870
+ };
871
+ if (stdinInputSource !== undefined) {
872
+ input.stdinInputSource = stdinInputSource;
873
+ }
874
+ if (sessionId) {
875
+ input.sessionId = sessionId;
876
+ }
877
+ if (modulePlanExecutionId) {
878
+ input.modulePlanExecutionId = modulePlanExecutionId;
879
+ }
880
+ if (suppressModulePlanStreamStart) {
881
+ input.suppressModulePlanStreamStart = true;
882
+ }
883
+ if (spans) {
884
+ input.metricsSpans = spans;
885
+ }
886
+ return {
887
+ input,
888
+ spans,
889
+ ...(traceDir !== undefined ? { traceDir } : {}),
890
+ env
891
+ };
892
+ }
893
+ function classifyInvokeMode(input) {
894
+ if (input.command === "rg" && input.restArgs[0] === "--") {
895
+ return "process";
896
+ }
897
+ if (input.command === "tsc" && input.restArgs[0] === "--") {
898
+ return "process";
899
+ }
900
+ if ((0, core_1.isRtkPassthroughCommand)(input.command) && input.restArgs[0] === "--") {
901
+ return "process";
902
+ }
903
+ if (canRunViaCliStream(input)) {
904
+ return "stream";
905
+ }
906
+ return "structured";
907
+ }
908
+ function buildExecRequestFromInvoke(request) {
909
+ const supported = ((request.input.command === "rg" || request.input.command === "tsc" || (0, core_1.isRtkPassthroughCommand)(request.input.command)) &&
910
+ request.input.restArgs[0] === "--");
911
+ if (!supported) {
912
+ throw new errors_1.CliError("UNSUPPORTED_INVOKE_PROCESS_COMMAND", `Unsupported process invocation: ${request.input.command}`, {
913
+ supported: ["rg --", "tsc --", ...core_1.RTK_PASSTHROUGH_COMMANDS.map((command) => `${command} --`)]
914
+ });
915
+ }
916
+ const execRequest = {
917
+ command: request.input.command,
918
+ restArgs: request.input.restArgs.slice(1),
919
+ cwd: request.input.cwd,
920
+ env: parseExecEnv(request.params)
921
+ };
922
+ if (request.params.has("stdin")) {
923
+ execRequest.stdinText = request.params.get("stdin") ?? "";
924
+ }
925
+ return execRequest;
926
+ }
927
+ function parseCliFormEnv(params) {
928
+ const env = {};
929
+ const entries = [
930
+ [env_vars_1.CLI_ENV.metrics, params.get("metrics") ?? ""],
931
+ [env_vars_1.CLI_ENV.metricsDir, params.get("metricsDir") ?? ""],
932
+ [env_vars_1.CLI_ENV.metricsTag, params.get("metricsTag") ?? ""],
933
+ [env_vars_1.CLI_ENV.mutationImpactMetrics, params.get("mutationImpactMetrics") ?? ""],
934
+ [env_vars_1.CLI_ENV.mutationImpactStream, params.get("mutationImpactStream") ?? ""],
935
+ [env_vars_1.CLI_ENV.testMoveToFileFailEntity, params.get("testMoveToFileFailEntity") ?? ""],
936
+ [env_vars_1.CLI_ENV.testPostMutationCyclesDelayMs, params.get("testPostMutationCyclesDelayMs") ?? ""],
937
+ [env_vars_1.CLI_ENV.testRefactorBatchDelayMs, params.get("testRefactorBatchDelayMs") ?? ""],
938
+ [env_vars_1.CLI_ENV.testRenameDelayMs, params.get("testRenameDelayMs") ?? ""],
939
+ [env_vars_1.CLI_ENV.testFileMoveToDirDelayMs, params.get("testFileMoveToDirDelayMs") ?? ""],
940
+ [env_vars_1.CLI_ENV.testFileMoveToDirRowDelayMs, params.get("testFileMoveToDirRowDelayMs") ?? ""],
941
+ [env_vars_1.CLI_ENV.testFileMoveToDirImportsDelayMs, params.get("testFileMoveToDirImportsDelayMs") ?? ""],
942
+ [env_vars_1.CLI_ENV.testFileMoveToDirFailImports, params.get("testFileMoveToDirFailImports") ?? ""],
943
+ [env_vars_1.CLI_ENV.testFileRenameDelayMs, params.get("testFileRenameDelayMs") ?? ""],
944
+ [env_vars_1.CLI_ENV.testFileRenameRowDelayMs, params.get("testFileRenameRowDelayMs") ?? ""],
945
+ [env_vars_1.CLI_ENV.testFileRenameImportsDelayMs, params.get("testFileRenameImportsDelayMs") ?? ""],
946
+ [env_vars_1.CLI_ENV.testFileRenameFailImports, params.get("testFileRenameFailImports") ?? ""],
947
+ [env_vars_1.CLI_ENV.testFileRefactorBatchDelayMs, params.get("testFileRefactorBatchDelayMs") ?? ""],
948
+ [env_vars_1.CLI_ENV.testFileRefactorBatchRowDelayMs, params.get("testFileRefactorBatchRowDelayMs") ?? ""],
949
+ [env_vars_1.CLI_ENV.testFileRefactorBatchImportsDelayMs, params.get("testFileRefactorBatchImportsDelayMs") ?? ""],
950
+ [env_vars_1.CLI_ENV.testFileRefactorBatchFailImports, params.get("testFileRefactorBatchFailImports") ?? ""],
951
+ [env_vars_1.CLI_ENV.testFileRefactorBatchCrashAfterFsMove, params.get("testFileRefactorBatchCrashAfterFsMove") ?? ""],
952
+ [env_vars_1.CLI_ENV.disableFileMutationImportPostProcess, params.get("disableFileMutationImportPostProcess") ?? ""],
953
+ [env_vars_1.CLI_ENV.disableFileMoveImportPostProcess, params.get("disableFileMoveImportPostProcess") ?? ""],
954
+ [env_vars_1.CLI_ENV.modulePlanSyncWaitMs, params.get("modulePlanSyncWaitMs") ?? ""],
955
+ [env_vars_1.CLI_ENV.refactorBatchSyncWaitMs, params.get("refactorBatchSyncWaitMs") ?? ""],
956
+ [env_vars_1.CLI_ENV.renameSyncWaitMs, params.get("renameSyncWaitMs") ?? ""],
957
+ [env_vars_1.CLI_ENV.fileMoveToDirSyncWaitMs, params.get("fileMoveToDirSyncWaitMs") ?? ""],
958
+ [env_vars_1.CLI_ENV.fileRenameSyncWaitMs, params.get("fileRenameSyncWaitMs") ?? ""],
959
+ [env_vars_1.CLI_ENV.fileRefactorBatchSyncWaitMs, params.get("fileRefactorBatchSyncWaitMs") ?? ""],
960
+ [env_vars_1.CLI_ENV.modulePlanDebugTimeline, params.get("modulePlanDebugTimeline") ?? ""],
961
+ [env_vars_1.CLI_ENV.trace, params.get("trace") ?? ""],
962
+ [env_vars_1.CLI_ENV.failureSnapshots, params.get("failureSnapshots") ?? ""],
963
+ [env_vars_1.CLI_ENV.productStorageDir, params.get("productStorageDir") ?? ""],
964
+ [env_vars_1.CLI_ENV.helpShell, params.get(`env.${env_vars_1.CLI_ENV.helpShell}`) ?? ""]
965
+ ];
966
+ for (const [key, value] of entries) {
967
+ const trimmed = value.trim();
968
+ if (trimmed) {
969
+ env[key] = trimmed;
970
+ }
971
+ }
972
+ return env;
973
+ }
974
+ function nonEmptyString(value) {
975
+ if (value === null) {
976
+ return undefined;
977
+ }
978
+ const trimmed = value.trim();
979
+ return trimmed ? trimmed : undefined;
980
+ }
981
+ function startCliFormTrace(cliRequest, startedAtMs) {
982
+ if (!cliRequest.traceDir) {
983
+ return null;
984
+ }
985
+ return (0, trace_1.startTrace)({
986
+ cwd: cliRequest.input.cwd,
987
+ argv: [cliRequest.input.command, ...cliRequest.input.restArgs],
988
+ command: cliRequest.input.command,
989
+ restArgs: cliRequest.input.restArgs,
990
+ ...(cliRequest.input.stdinPayload !== undefined ? { stdinPayload: cliRequest.input.stdinPayload } : {}),
991
+ ...(cliRequest.input.stdinInputSource !== undefined ? { stdinSource: cliRequest.input.stdinInputSource } : {}),
992
+ traceDir: cliRequest.traceDir,
993
+ startedAtMs
994
+ });
995
+ }
996
+ function completeCliFormTrace(trace, cliRequest, output, exitCode, startedAtMs) {
997
+ if (!trace?.enabled || !cliRequest) {
998
+ return;
999
+ }
1000
+ const envelope = (0, presentation_1.createCliPresentationEnvelope)(output);
1001
+ trace.complete({
1002
+ output: envelope.tracePayload,
1003
+ stdoutText: envelope.text ? `${envelope.text.trimEnd()}\n` : `${JSON.stringify(envelope.tracePayload, null, 2)}\n`,
1004
+ exitCode: output.ok === false ? 1 : exitCode,
1005
+ durationMs: Date.now() - startedAtMs
1006
+ });
1007
+ }
1008
+ function prepareCliPresentationPayload(output) {
1009
+ return (0, presentation_1.createCliPresentationEnvelope)(output).payload;
1010
+ }
1011
+ function startCliProgressStream(response, input) {
1012
+ if (!shouldStreamModulePlanProgress(input)) {
1013
+ return null;
1014
+ }
1015
+ const executionId = input.modulePlanExecutionId ?? (0, module_plan_cache_1.buildModulePlanExecutionId)();
1016
+ input.modulePlanExecutionId = executionId;
1017
+ const streamStartedAtMs = Date.now();
1018
+ const timeoutEstimate = estimateModulePlanTimeoutForStream(input);
1019
+ const estimatedLine = timeoutEstimate
1020
+ ? `\nestimated: ${(0, module_plan_timeout_1.formatModulePlanTimeoutEstimate)(timeoutEstimate.estimatedDurationMs)}`
1021
+ : "";
1022
+ if (!input.suppressModulePlanStreamStart) {
1023
+ writeStreamEvent(response, {
1024
+ type: "start",
1025
+ text: `modulePlan.${input.restArgs[0] ?? "execute"} ${executionId}${estimatedLine}`,
1026
+ data: {
1027
+ operation: `modulePlan.${input.restArgs[0] ?? "execute"}`,
1028
+ executionId,
1029
+ ...(timeoutEstimate ? {
1030
+ estimatedTimeoutMs: timeoutEstimate.recommendedTimeoutMs,
1031
+ estimatedDurationMs: timeoutEstimate.estimatedDurationMs,
1032
+ suggestedFirstCheckMs: timeoutEstimate.suggestedFirstCheckMs,
1033
+ rowCount: timeoutEstimate.rowCount,
1034
+ symbolCount: timeoutEstimate.symbolCount
1035
+ } : {})
1036
+ }
1037
+ });
1038
+ }
1039
+ if (!MODULE_PLAN_PROGRESS_STREAM_ENABLED) {
1040
+ return null;
1041
+ }
1042
+ let lastHeartbeatAtMs = streamStartedAtMs;
1043
+ return setInterval(() => {
1044
+ try {
1045
+ const status = (0, module_plan_cache_1.readModulePlanExecutionStatus)(input.cwd, executionId);
1046
+ const executionStartedAtMs = Date.parse(status.startedAt);
1047
+ if (Number.isFinite(executionStartedAtMs) && executionStartedAtMs + 1_000 < streamStartedAtMs) {
1048
+ lastHeartbeatAtMs = writeModulePlanHeartbeat(response, lastHeartbeatAtMs);
1049
+ return;
1050
+ }
1051
+ const hasVisibleProgress = status.completedRows > 0 || status.failedRows > 0 || status.filesWritten.length > 0;
1052
+ if (!hasVisibleProgress) {
1053
+ lastHeartbeatAtMs = writeModulePlanHeartbeat(response, lastHeartbeatAtMs);
1054
+ return;
1055
+ }
1056
+ writeStreamEvent(response, {
1057
+ type: "progress",
1058
+ text: `progress: ${status.completedRows}/${status.rowCount} rows${formatModulePlanEntityProgress(status.completedEntities, status.entityCount)}, ${status.filesWritten.length} files`,
1059
+ data: {
1060
+ operation: status.operation,
1061
+ executionId: status.executionId,
1062
+ status: status.status,
1063
+ completedRows: status.completedRows,
1064
+ failedRows: status.failedRows,
1065
+ rowCount: status.rowCount,
1066
+ completedEntities: status.completedEntities,
1067
+ entityCount: status.entityCount,
1068
+ filesWritten: status.filesWritten.length
1069
+ }
1070
+ });
1071
+ }
1072
+ catch {
1073
+ lastHeartbeatAtMs = writeModulePlanHeartbeat(response, lastHeartbeatAtMs);
1074
+ }
1075
+ }, 5_000);
1076
+ }
1077
+ function writeModulePlanHeartbeat(response, lastHeartbeatAtMs) {
1078
+ if (!MODULE_PLAN_HEARTBEAT_ENABLED) {
1079
+ return lastHeartbeatAtMs;
1080
+ }
1081
+ const now = Date.now();
1082
+ if (now - lastHeartbeatAtMs < 30_000) {
1083
+ return lastHeartbeatAtMs;
1084
+ }
1085
+ writeStreamEvent(response, {
1086
+ type: "progress",
1087
+ text: "modulePlan still running",
1088
+ data: {
1089
+ operation: "modulePlan",
1090
+ status: "running"
1091
+ }
1092
+ });
1093
+ return now;
1094
+ }
1095
+ function formatModulePlanEntityProgress(completedEntities, entityCount) {
1096
+ if (!entityCount || entityCount <= 0) {
1097
+ return "";
1098
+ }
1099
+ const completed = completedEntities ?? 0;
1100
+ return `, ${Math.floor((completed / entityCount) * 100)}% entities`;
1101
+ }
1102
+ function shouldStreamModulePlanProgress(input) {
1103
+ return isSessionModulePlanMutation(input);
1104
+ }
1105
+ function estimateModulePlanTimeoutForStream(input) {
1106
+ const mutateModulePlanRequest = readSingleModulePlanMutateRequest(input);
1107
+ if (mutateModulePlanRequest) {
1108
+ return (0, module_plan_timeout_1.estimateModulePlanTimeoutFromRequest)(mutateModulePlanRequest);
1109
+ }
1110
+ const action = input.restArgs[0] ?? "";
1111
+ if (action === "execute") {
1112
+ return (0, module_plan_timeout_1.estimateModulePlanTimeoutFromRequest)(input.stdinPayload);
1113
+ }
1114
+ if (action !== "apply") {
1115
+ return null;
1116
+ }
1117
+ const planId = readModulePlanApplyPlanId(input.restArgs);
1118
+ if (!planId) {
1119
+ return null;
1120
+ }
1121
+ try {
1122
+ return (0, module_plan_timeout_1.estimateModulePlanTimeoutFromRequest)((0, module_plan_cache_1.readModulePlanRecord)(input.cwd, planId).normalizedRequest);
1123
+ }
1124
+ catch {
1125
+ return null;
1126
+ }
1127
+ }
1128
+ function ensureSessionModulePlanExecutionId(input) {
1129
+ if (input.modulePlanExecutionId || !isSessionModulePlanMutation(input)) {
1130
+ return;
1131
+ }
1132
+ input.modulePlanExecutionId = (0, module_plan_cache_1.buildModulePlanExecutionId)();
1133
+ }
1134
+ function isSessionModulePlanMutation(input) {
1135
+ if (input.command === "modulePlan") {
1136
+ const action = input.restArgs[0] ?? "";
1137
+ return action === "execute" || action === "apply";
1138
+ }
1139
+ return Boolean(readSingleModulePlanMutateRequest(input));
1140
+ }
1141
+ function readSingleModulePlanMutateRequest(input) {
1142
+ if (input.command !== "mutate" || input.restArgs[0] !== "execute") {
1143
+ return null;
1144
+ }
1145
+ if (!isJsonObject(input.stdinPayload)) {
1146
+ return null;
1147
+ }
1148
+ const segments = Array.isArray(input.stdinPayload.segments) ? input.stdinPayload.segments.filter(isJsonObject) : [];
1149
+ if (segments.length !== 1 || segments[0]?.kind !== "modulePlan") {
1150
+ return null;
1151
+ }
1152
+ const segment = segments[0];
1153
+ const sourceFile = typeof segment.sourceFile === "string" ? segment.sourceFile : null;
1154
+ const modules = Array.isArray(segment.modules) ? segment.modules.filter(isJsonObject) : [];
1155
+ if (!sourceFile || modules.length === 0) {
1156
+ return null;
1157
+ }
1158
+ return {
1159
+ sourceFile,
1160
+ modules: modules.map((module) => ({
1161
+ target: typeof module.targetFile === "string"
1162
+ ? module.targetFile
1163
+ : typeof module.target === "string"
1164
+ ? module.target
1165
+ : "",
1166
+ entities: readStringArray(module.symbols).length > 0 ? readStringArray(module.symbols) : readStringArray(module.entities)
1167
+ }))
1168
+ };
1169
+ }
1170
+ function readStringArray(value) {
1171
+ return Array.isArray(value) ? value.filter((item) => typeof item === "string") : [];
1172
+ }
1173
+ function isJsonObject(value) {
1174
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
1175
+ }
1176
+ function readModulePlanApplyPlanId(restArgs) {
1177
+ const flagIndex = restArgs.indexOf("--plan");
1178
+ if (flagIndex >= 0) {
1179
+ const value = restArgs[flagIndex + 1];
1180
+ return value && !value.startsWith("--") ? value : null;
1181
+ }
1182
+ const positional = restArgs.slice(1).find((arg) => !arg.startsWith("--"));
1183
+ return positional ?? null;
1184
+ }
1185
+ async function runSessionServerCli() {
1186
+ const command = process.argv[3] || "status";
1187
+ if (command !== "serve") {
1188
+ (0, stdout_1.printJson)((0, errors_1.errorPayload)(new errors_1.CliError("UNKNOWN_SESSION_COMMAND", `Unknown aib session command: ${command}`)));
1189
+ process.exitCode = 1;
1190
+ return;
1191
+ }
1192
+ const server = new CliSessionServer();
1193
+ await server.serve();
1194
+ }