@1mcp/agent 0.39.5 → 0.40.0-beta.0

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 (517) hide show
  1. package/README.md +14 -7
  2. package/build/admin/assets/{admin-BackendLogsWorkspace-BKavXT9B.js → admin-BackendLogsWorkspace-DnPzXW3E.js} +1 -1
  3. package/build/admin/assets/{admin-InstructionTemplatesWorkspace-CvG4EPdZ.js → admin-InstructionTemplatesWorkspace-B7beKEgz.js} +1 -1
  4. package/build/admin/assets/{admin-OAuthServicesWorkspace-BzrCR7Bi.js → admin-OAuthServicesWorkspace-Bu74Bzt5.js} +1 -1
  5. package/build/admin/assets/{admin-PresetAuthoringWorkspace-BboJVBFl.js → admin-PresetAuthoringWorkspace-053b1zwU.js} +1 -1
  6. package/build/admin/assets/{admin-console-BpUgmlrR.js → admin-console-DVuqABnE.js} +3 -3
  7. package/build/admin/assets/admin-icons-wOzB38gm.js +1 -0
  8. package/build/admin/assets/admin-vendor-BLZ1Mauf.js +3 -0
  9. package/build/admin/assets/admin-vendor-BdHKHno1.js +1 -0
  10. package/build/admin/assets/admin-vendor-BqYiU41k.js +51 -0
  11. package/build/admin/assets/admin-vendor-C291Vs-N.js +3 -0
  12. package/build/admin/assets/admin-vendor-VzhcFgoy.js +1 -0
  13. package/build/admin/index.html +7 -5
  14. package/build/application/backendPreparationAdmission.d.ts +77 -0
  15. package/build/application/backendPreparationAdmission.d.ts.map +1 -0
  16. package/build/application/backendPreparationAdmission.js +423 -0
  17. package/build/application/backendPreparationAdmission.js.map +1 -0
  18. package/build/application/backendPreparationCoordinator.d.ts +122 -0
  19. package/build/application/backendPreparationCoordinator.d.ts.map +1 -0
  20. package/build/application/backendPreparationCoordinator.js +885 -0
  21. package/build/application/backendPreparationCoordinator.js.map +1 -0
  22. package/build/application/projectLifecycle.d.ts +49 -0
  23. package/build/application/projectLifecycle.d.ts.map +1 -0
  24. package/build/application/projectLifecycle.js +228 -0
  25. package/build/application/projectLifecycle.js.map +1 -0
  26. package/build/cli.d.ts.map +1 -1
  27. package/build/cli.js +39 -17
  28. package/build/cli.js.map +1 -1
  29. package/build/commands/admin/index.d.ts.map +1 -1
  30. package/build/commands/admin/index.js +2 -6
  31. package/build/commands/admin/index.js.map +1 -1
  32. package/build/commands/app/index.d.ts.map +1 -1
  33. package/build/commands/app/index.js +5 -17
  34. package/build/commands/app/index.js.map +1 -1
  35. package/build/commands/auth/index.d.ts.map +1 -1
  36. package/build/commands/auth/index.js +2 -7
  37. package/build/commands/auth/index.js.map +1 -1
  38. package/build/commands/bootstrap/bootstrap.d.ts +38 -0
  39. package/build/commands/bootstrap/bootstrap.d.ts.map +1 -0
  40. package/build/commands/bootstrap/bootstrap.js +265 -0
  41. package/build/commands/bootstrap/bootstrap.js.map +1 -0
  42. package/build/commands/bootstrap/bootstrapOwnership.d.ts +13 -0
  43. package/build/commands/bootstrap/bootstrapOwnership.d.ts.map +1 -0
  44. package/build/commands/bootstrap/bootstrapOwnership.js +112 -0
  45. package/build/commands/bootstrap/bootstrapOwnership.js.map +1 -0
  46. package/build/commands/bootstrap/index.d.ts +3 -0
  47. package/build/commands/bootstrap/index.d.ts.map +1 -0
  48. package/build/commands/bootstrap/index.js +22 -0
  49. package/build/commands/bootstrap/index.js.map +1 -0
  50. package/build/commands/cliSetup/index.d.ts.map +1 -1
  51. package/build/commands/cliSetup/index.js +3 -4
  52. package/build/commands/cliSetup/index.js.map +1 -1
  53. package/build/commands/cliSetup/installPreparationSkill.d.ts +8 -0
  54. package/build/commands/cliSetup/installPreparationSkill.d.ts.map +1 -0
  55. package/build/commands/cliSetup/installPreparationSkill.js +201 -0
  56. package/build/commands/cliSetup/installPreparationSkill.js.map +1 -0
  57. package/build/commands/cliSetup/preparationSkill.generated.d.ts +2 -0
  58. package/build/commands/cliSetup/preparationSkill.generated.d.ts.map +1 -0
  59. package/build/commands/cliSetup/preparationSkill.generated.js +8 -0
  60. package/build/commands/cliSetup/preparationSkill.generated.js.map +1 -0
  61. package/build/commands/cliSetup/setupFiles.d.ts +5 -1
  62. package/build/commands/cliSetup/setupFiles.d.ts.map +1 -1
  63. package/build/commands/cliSetup/setupFiles.js +54 -37
  64. package/build/commands/cliSetup/setupFiles.js.map +1 -1
  65. package/build/commands/inspect/index.d.ts.map +1 -1
  66. package/build/commands/inspect/index.js +4 -4
  67. package/build/commands/inspect/index.js.map +1 -1
  68. package/build/commands/inspect/inspect.d.ts +2 -1
  69. package/build/commands/inspect/inspect.d.ts.map +1 -1
  70. package/build/commands/inspect/inspect.js +10 -5
  71. package/build/commands/inspect/inspect.js.map +1 -1
  72. package/build/commands/inspect/inspectUtils.js +3 -0
  73. package/build/commands/inspect/inspectUtils.js.map +1 -1
  74. package/build/commands/instructions/index.d.ts.map +1 -1
  75. package/build/commands/instructions/index.js +8 -3
  76. package/build/commands/instructions/index.js.map +1 -1
  77. package/build/commands/instructions/instructions.d.ts +3 -1
  78. package/build/commands/instructions/instructions.d.ts.map +1 -1
  79. package/build/commands/instructions/instructions.js +24 -0
  80. package/build/commands/instructions/instructions.js.map +1 -1
  81. package/build/commands/instructions/instructionsUtils.d.ts +2 -0
  82. package/build/commands/instructions/instructionsUtils.d.ts.map +1 -1
  83. package/build/commands/instructions/instructionsUtils.js +14 -4
  84. package/build/commands/instructions/instructionsUtils.js.map +1 -1
  85. package/build/commands/mcp/index.d.ts.map +1 -1
  86. package/build/commands/mcp/index.js +16 -21
  87. package/build/commands/mcp/index.js.map +1 -1
  88. package/build/commands/mcp/installSource.d.ts +3 -1
  89. package/build/commands/mcp/installSource.d.ts.map +1 -1
  90. package/build/commands/mcp/installSource.js +2 -2
  91. package/build/commands/mcp/installSource.js.map +1 -1
  92. package/build/commands/mcp/knownServerSetup.d.ts +4 -0
  93. package/build/commands/mcp/knownServerSetup.d.ts.map +1 -0
  94. package/build/commands/mcp/knownServerSetup.js +102 -0
  95. package/build/commands/mcp/knownServerSetup.js.map +1 -0
  96. package/build/commands/mcp/setup.d.ts +28 -0
  97. package/build/commands/mcp/setup.d.ts.map +1 -0
  98. package/build/commands/mcp/setup.js +56 -0
  99. package/build/commands/mcp/setup.js.map +1 -0
  100. package/build/commands/mcp/tools.d.ts.map +1 -1
  101. package/build/commands/mcp/tools.js +3 -3
  102. package/build/commands/mcp/tools.js.map +1 -1
  103. package/build/commands/preparation/index.d.ts +3 -0
  104. package/build/commands/preparation/index.d.ts.map +1 -0
  105. package/build/commands/preparation/index.js +55 -0
  106. package/build/commands/preparation/index.js.map +1 -0
  107. package/build/commands/preparation/preparation.d.ts +18 -0
  108. package/build/commands/preparation/preparation.d.ts.map +1 -0
  109. package/build/commands/preparation/preparation.js +102 -0
  110. package/build/commands/preparation/preparation.js.map +1 -0
  111. package/build/commands/preset/index.d.ts.map +1 -1
  112. package/build/commands/preset/index.js +4 -51
  113. package/build/commands/preset/index.js.map +1 -1
  114. package/build/commands/project/index.d.ts +3 -0
  115. package/build/commands/project/index.d.ts.map +1 -0
  116. package/build/commands/project/index.js +40 -0
  117. package/build/commands/project/index.js.map +1 -0
  118. package/build/commands/project/project.d.ts +34 -0
  119. package/build/commands/project/project.d.ts.map +1 -0
  120. package/build/commands/project/project.js +119 -0
  121. package/build/commands/project/project.js.map +1 -0
  122. package/build/commands/proxy/index.d.ts +2 -1
  123. package/build/commands/proxy/index.d.ts.map +1 -1
  124. package/build/commands/proxy/index.js +6 -46
  125. package/build/commands/proxy/index.js.map +1 -1
  126. package/build/commands/proxy/proxy.d.ts.map +1 -1
  127. package/build/commands/proxy/proxy.js +7 -1
  128. package/build/commands/proxy/proxy.js.map +1 -1
  129. package/build/commands/registry/index.d.ts.map +1 -1
  130. package/build/commands/registry/index.js +16 -20
  131. package/build/commands/registry/index.js.map +1 -1
  132. package/build/commands/run/index.d.ts.map +1 -1
  133. package/build/commands/run/index.js +9 -3
  134. package/build/commands/run/index.js.map +1 -1
  135. package/build/commands/run/run.d.ts +4 -1
  136. package/build/commands/run/run.d.ts.map +1 -1
  137. package/build/commands/run/run.js +80 -14
  138. package/build/commands/run/run.js.map +1 -1
  139. package/build/commands/serve/cooperativeRuntime.d.ts.map +1 -1
  140. package/build/commands/serve/cooperativeRuntime.js +2 -1
  141. package/build/commands/serve/cooperativeRuntime.js.map +1 -1
  142. package/build/commands/serve/index.d.ts.map +1 -1
  143. package/build/commands/serve/index.js +57 -39
  144. package/build/commands/serve/index.js.map +1 -1
  145. package/build/commands/serve/serveStatus.d.ts.map +1 -1
  146. package/build/commands/serve/serveStatus.js +3 -0
  147. package/build/commands/serve/serveStatus.js.map +1 -1
  148. package/build/commands/serve/serveStop.d.ts.map +1 -1
  149. package/build/commands/serve/serveStop.js +38 -6
  150. package/build/commands/serve/serveStop.js.map +1 -1
  151. package/build/commands/shared/agentSession.d.ts +5 -0
  152. package/build/commands/shared/agentSession.d.ts.map +1 -0
  153. package/build/commands/shared/agentSession.js +75 -0
  154. package/build/commands/shared/agentSession.js.map +1 -0
  155. package/build/commands/shared/apiClient.d.ts +2 -0
  156. package/build/commands/shared/apiClient.d.ts.map +1 -1
  157. package/build/commands/shared/apiClient.js +10 -6
  158. package/build/commands/shared/apiClient.js.map +1 -1
  159. package/build/commands/shared/cliContext.d.ts +2 -1
  160. package/build/commands/shared/cliContext.d.ts.map +1 -1
  161. package/build/commands/shared/cliContext.js +2 -1
  162. package/build/commands/shared/cliContext.js.map +1 -1
  163. package/build/commands/shared/clientSurfaceAttachment.d.ts +7 -1
  164. package/build/commands/shared/clientSurfaceAttachment.d.ts.map +1 -1
  165. package/build/commands/shared/clientSurfaceAttachment.js +221 -140
  166. package/build/commands/shared/clientSurfaceAttachment.js.map +1 -1
  167. package/build/commands/shared/inspectApiSchemas.d.ts +4 -4
  168. package/build/commands/shared/projectOwnerStorage.d.ts +8 -0
  169. package/build/commands/shared/projectOwnerStorage.d.ts.map +1 -0
  170. package/build/commands/shared/projectOwnerStorage.js +63 -0
  171. package/build/commands/shared/projectOwnerStorage.js.map +1 -0
  172. package/build/commands/shared/projectOwnerStore.d.ts +78 -0
  173. package/build/commands/shared/projectOwnerStore.d.ts.map +1 -0
  174. package/build/commands/shared/projectOwnerStore.js +482 -0
  175. package/build/commands/shared/projectOwnerStore.js.map +1 -0
  176. package/build/commands/shared/projectSelectionOptions.d.ts +24 -0
  177. package/build/commands/shared/projectSelectionOptions.d.ts.map +1 -0
  178. package/build/commands/shared/projectSelectionOptions.js +20 -0
  179. package/build/commands/shared/projectSelectionOptions.js.map +1 -0
  180. package/build/commands/shared/serveTargetResolver.d.ts +7 -1
  181. package/build/commands/shared/serveTargetResolver.d.ts.map +1 -1
  182. package/build/commands/shared/serveTargetResolver.js +99 -4
  183. package/build/commands/shared/serveTargetResolver.js.map +1 -1
  184. package/build/commands/target/index.d.ts.map +1 -1
  185. package/build/commands/target/index.js +6 -13
  186. package/build/commands/target/index.js.map +1 -1
  187. package/build/commands/wait/index.d.ts.map +1 -1
  188. package/build/commands/wait/index.js +3 -3
  189. package/build/commands/wait/index.js.map +1 -1
  190. package/build/commands/wait/wait.d.ts +2 -1
  191. package/build/commands/wait/wait.d.ts.map +1 -1
  192. package/build/commands/wait/wait.js.map +1 -1
  193. package/build/config/configLoader.d.ts.map +1 -1
  194. package/build/config/configLoader.js +5 -1
  195. package/build/config/configLoader.js.map +1 -1
  196. package/build/config/configManager.d.ts.map +1 -1
  197. package/build/config/configManager.js +5 -1
  198. package/build/config/configManager.js.map +1 -1
  199. package/build/config/projectConfigLoader.d.ts +4 -0
  200. package/build/config/projectConfigLoader.d.ts.map +1 -1
  201. package/build/config/projectConfigLoader.js +129 -28
  202. package/build/config/projectConfigLoader.js.map +1 -1
  203. package/build/config/projectConfigTypes.d.ts +7 -0
  204. package/build/config/projectConfigTypes.d.ts.map +1 -1
  205. package/build/config/projectConfigTypes.js +1 -0
  206. package/build/config/projectConfigTypes.js.map +1 -1
  207. package/build/constants/cliTimeouts.d.ts +4 -0
  208. package/build/constants/cliTimeouts.d.ts.map +1 -0
  209. package/build/constants/cliTimeouts.js +4 -0
  210. package/build/constants/cliTimeouts.js.map +1 -0
  211. package/build/constants/mcp.d.ts +1 -1
  212. package/build/constants/mcp.d.ts.map +1 -1
  213. package/build/constants/mcp.js +1 -1
  214. package/build/constants/mcp.js.map +1 -1
  215. package/build/core/capabilities/capabilityCatalog.d.ts +7 -0
  216. package/build/core/capabilities/capabilityCatalog.d.ts.map +1 -1
  217. package/build/core/capabilities/capabilityCatalog.js +58 -2
  218. package/build/core/capabilities/capabilityCatalog.js.map +1 -1
  219. package/build/core/capabilities/capabilityPagination.d.ts +12 -4
  220. package/build/core/capabilities/capabilityPagination.d.ts.map +1 -1
  221. package/build/core/capabilities/capabilityPagination.js +15 -2
  222. package/build/core/capabilities/capabilityPagination.js.map +1 -1
  223. package/build/core/capabilities/capabilityVisibility.d.ts +3 -0
  224. package/build/core/capabilities/capabilityVisibility.d.ts.map +1 -1
  225. package/build/core/capabilities/capabilityVisibility.js.map +1 -1
  226. package/build/core/capabilities/lazyLoadingOrchestrator.d.ts +2 -1
  227. package/build/core/capabilities/lazyLoadingOrchestrator.d.ts.map +1 -1
  228. package/build/core/capabilities/lazyLoadingOrchestrator.js +2 -2
  229. package/build/core/capabilities/lazyLoadingOrchestrator.js.map +1 -1
  230. package/build/core/capabilities/metaToolProvider.d.ts +2 -2
  231. package/build/core/capabilities/metaToolProvider.d.ts.map +1 -1
  232. package/build/core/capabilities/metaToolProvider.js +2 -2
  233. package/build/core/capabilities/metaToolProvider.js.map +1 -1
  234. package/build/core/capabilities/runtimeCapabilityCatalog.d.ts +1 -0
  235. package/build/core/capabilities/runtimeCapabilityCatalog.d.ts.map +1 -1
  236. package/build/core/capabilities/runtimeCapabilityCatalog.js +23 -9
  237. package/build/core/capabilities/runtimeCapabilityCatalog.js.map +1 -1
  238. package/build/core/context/projectOwner.d.ts +16 -0
  239. package/build/core/context/projectOwner.d.ts.map +1 -0
  240. package/build/core/context/projectOwner.js +33 -0
  241. package/build/core/context/projectOwner.js.map +1 -0
  242. package/build/core/context/projectPreparationAuthority.d.ts +37 -0
  243. package/build/core/context/projectPreparationAuthority.d.ts.map +1 -0
  244. package/build/core/context/projectPreparationAuthority.js +113 -0
  245. package/build/core/context/projectPreparationAuthority.js.map +1 -0
  246. package/build/core/instructions/inspectionGuidance.d.ts +2 -0
  247. package/build/core/instructions/inspectionGuidance.d.ts.map +1 -0
  248. package/build/core/instructions/inspectionGuidance.js +2 -0
  249. package/build/core/instructions/inspectionGuidance.js.map +1 -0
  250. package/build/core/instructions/instructionAggregator.d.ts +1 -0
  251. package/build/core/instructions/instructionAggregator.d.ts.map +1 -1
  252. package/build/core/instructions/instructionAggregator.js +2 -2
  253. package/build/core/instructions/instructionAggregator.js.map +1 -1
  254. package/build/core/instructions/instructionsDistribution.d.ts +5 -0
  255. package/build/core/instructions/instructionsDistribution.d.ts.map +1 -1
  256. package/build/core/instructions/instructionsDistribution.js +72 -15
  257. package/build/core/instructions/instructionsDistribution.js.map +1 -1
  258. package/build/core/instructions/preparationGuidance.d.ts +3 -0
  259. package/build/core/instructions/preparationGuidance.d.ts.map +1 -0
  260. package/build/core/instructions/preparationGuidance.js +14 -0
  261. package/build/core/instructions/preparationGuidance.js.map +1 -0
  262. package/build/core/instructions/sessionGuidance.d.ts +3 -0
  263. package/build/core/instructions/sessionGuidance.d.ts.map +1 -0
  264. package/build/core/instructions/sessionGuidance.js +25 -0
  265. package/build/core/instructions/sessionGuidance.js.map +1 -0
  266. package/build/core/instructions/templateTypes.d.ts +3 -1
  267. package/build/core/instructions/templateTypes.d.ts.map +1 -1
  268. package/build/core/instructions/templateTypes.js +15 -5
  269. package/build/core/instructions/templateTypes.js.map +1 -1
  270. package/build/core/protocol/requestHandlerUtils.d.ts.map +1 -1
  271. package/build/core/protocol/requestHandlerUtils.js +23 -4
  272. package/build/core/protocol/requestHandlerUtils.js.map +1 -1
  273. package/build/core/server/connectionResolver.d.ts +5 -0
  274. package/build/core/server/connectionResolver.d.ts.map +1 -1
  275. package/build/core/server/connectionResolver.js +11 -0
  276. package/build/core/server/connectionResolver.js.map +1 -1
  277. package/build/core/server/pidFileManager.d.ts +20 -5
  278. package/build/core/server/pidFileManager.d.ts.map +1 -1
  279. package/build/core/server/pidFileManager.js +34 -15
  280. package/build/core/server/pidFileManager.js.map +1 -1
  281. package/build/core/server/processIdentity.d.ts +18 -0
  282. package/build/core/server/processIdentity.d.ts.map +1 -1
  283. package/build/core/server/processIdentity.js +13 -2
  284. package/build/core/server/processIdentity.js.map +1 -1
  285. package/build/core/server/runtimeLaunchIpc.d.ts +167 -2
  286. package/build/core/server/runtimeLaunchIpc.d.ts.map +1 -1
  287. package/build/core/server/runtimeOwnershipIdentityRepair.d.ts +21 -0
  288. package/build/core/server/runtimeOwnershipIdentityRepair.d.ts.map +1 -0
  289. package/build/core/server/runtimeOwnershipIdentityRepair.js +158 -0
  290. package/build/core/server/runtimeOwnershipIdentityRepair.js.map +1 -0
  291. package/build/core/server/runtimeReplacementConfig.d.ts +167 -2
  292. package/build/core/server/runtimeReplacementConfig.d.ts.map +1 -1
  293. package/build/core/server/runtimeScopeOwnership.d.ts +21 -2
  294. package/build/core/server/runtimeScopeOwnership.d.ts.map +1 -1
  295. package/build/core/server/runtimeScopeOwnership.js +145 -16
  296. package/build/core/server/runtimeScopeOwnership.js.map +1 -1
  297. package/build/core/tools/handlers/serverManagementHandler.d.ts +413 -7
  298. package/build/core/tools/handlers/serverManagementHandler.d.ts.map +1 -1
  299. package/build/core/tools/internal/adapters/helpers/configTransformers.d.ts +59 -1
  300. package/build/core/tools/internal/adapters/helpers/configTransformers.d.ts.map +1 -1
  301. package/build/core/tools/internal/schemas/index.d.ts +1 -1
  302. package/build/core/tools/internal/schemas/management.d.ts +1 -1
  303. package/build/core/types/server.d.ts +7 -1
  304. package/build/core/types/server.d.ts.map +1 -1
  305. package/build/core/types/transport.d.ts +249 -3
  306. package/build/core/types/transport.d.ts.map +1 -1
  307. package/build/core/types/transport.js +27 -0
  308. package/build/core/types/transport.js.map +1 -1
  309. package/build/domains/admin/adminInstructionPreviewRuntime.d.ts.map +1 -1
  310. package/build/domains/admin/adminInstructionPreviewRuntime.js +4 -1
  311. package/build/domains/admin/adminInstructionPreviewRuntime.js.map +1 -1
  312. package/build/domains/backend-preparation/adapterRegistry.d.ts +8 -0
  313. package/build/domains/backend-preparation/adapterRegistry.d.ts.map +1 -0
  314. package/build/domains/backend-preparation/adapterRegistry.js +15 -0
  315. package/build/domains/backend-preparation/adapterRegistry.js.map +1 -0
  316. package/build/domains/backend-preparation/builtInIntegrationDefinitions.d.ts +4 -0
  317. package/build/domains/backend-preparation/builtInIntegrationDefinitions.d.ts.map +1 -0
  318. package/build/domains/backend-preparation/builtInIntegrationDefinitions.js +3 -0
  319. package/build/domains/backend-preparation/builtInIntegrationDefinitions.js.map +1 -0
  320. package/build/domains/backend-preparation/configuredCommandAdapter.d.ts +88 -0
  321. package/build/domains/backend-preparation/configuredCommandAdapter.d.ts.map +1 -0
  322. package/build/domains/backend-preparation/configuredCommandAdapter.js +196 -0
  323. package/build/domains/backend-preparation/configuredCommandAdapter.js.map +1 -0
  324. package/build/domains/backend-preparation/configuredCommandProcess.d.ts +27 -0
  325. package/build/domains/backend-preparation/configuredCommandProcess.d.ts.map +1 -0
  326. package/build/domains/backend-preparation/configuredCommandProcess.js +183 -0
  327. package/build/domains/backend-preparation/configuredCommandProcess.js.map +1 -0
  328. package/build/domains/backend-preparation/contracts.d.ts +131 -0
  329. package/build/domains/backend-preparation/contracts.d.ts.map +1 -0
  330. package/build/domains/backend-preparation/contracts.js +2 -0
  331. package/build/domains/backend-preparation/contracts.js.map +1 -0
  332. package/build/domains/backend-preparation/integrationDefinitions.d.ts +171 -0
  333. package/build/domains/backend-preparation/integrationDefinitions.d.ts.map +1 -0
  334. package/build/domains/backend-preparation/integrationDefinitions.js +246 -0
  335. package/build/domains/backend-preparation/integrationDefinitions.js.map +1 -0
  336. package/build/domains/backend-preparation/policy.d.ts +50 -0
  337. package/build/domains/backend-preparation/policy.d.ts.map +1 -0
  338. package/build/domains/backend-preparation/policy.js +58 -0
  339. package/build/domains/backend-preparation/policy.js.map +1 -0
  340. package/build/domains/backend-preparation/scheduler.d.ts +18 -0
  341. package/build/domains/backend-preparation/scheduler.d.ts.map +1 -0
  342. package/build/domains/backend-preparation/scheduler.js +62 -0
  343. package/build/domains/backend-preparation/scheduler.js.map +1 -0
  344. package/build/domains/backend-preparation/service.d.ts +67 -0
  345. package/build/domains/backend-preparation/service.d.ts.map +1 -0
  346. package/build/domains/backend-preparation/service.js +709 -0
  347. package/build/domains/backend-preparation/service.js.map +1 -0
  348. package/build/domains/config-change/configChange.js +5 -5
  349. package/build/domains/config-change/configChange.js.map +1 -1
  350. package/build/domains/installation/knownServerCatalog.d.ts +14 -0
  351. package/build/domains/installation/knownServerCatalog.d.ts.map +1 -0
  352. package/build/domains/installation/knownServerCatalog.js +56 -0
  353. package/build/domains/installation/knownServerCatalog.js.map +1 -0
  354. package/build/domains/installation/knownServerSetup.d.ts +21 -0
  355. package/build/domains/installation/knownServerSetup.d.ts.map +1 -0
  356. package/build/domains/installation/knownServerSetup.js +330 -0
  357. package/build/domains/installation/knownServerSetup.js.map +1 -0
  358. package/build/domains/installation/knownServerSetupTypes.d.ts +34 -0
  359. package/build/domains/installation/knownServerSetupTypes.d.ts.map +1 -0
  360. package/build/domains/installation/knownServerSetupTypes.js +2 -0
  361. package/build/domains/installation/knownServerSetupTypes.js.map +1 -0
  362. package/build/domains/project-selection/projectBindingScope.d.ts +7 -0
  363. package/build/domains/project-selection/projectBindingScope.d.ts.map +1 -0
  364. package/build/domains/project-selection/projectBindingScope.js +9 -0
  365. package/build/domains/project-selection/projectBindingScope.js.map +1 -0
  366. package/build/domains/project-selection/projectPolicy.d.ts +11 -0
  367. package/build/domains/project-selection/projectPolicy.d.ts.map +1 -0
  368. package/build/domains/project-selection/projectPolicy.js +104 -0
  369. package/build/domains/project-selection/projectPolicy.js.map +1 -0
  370. package/build/domains/project-selection/projectSelection.d.ts +30 -0
  371. package/build/domains/project-selection/projectSelection.d.ts.map +1 -0
  372. package/build/domains/project-selection/projectSelection.js +124 -0
  373. package/build/domains/project-selection/projectSelection.js.map +1 -0
  374. package/build/globalOptions.d.ts +9 -0
  375. package/build/globalOptions.d.ts.map +1 -1
  376. package/build/globalOptions.js +13 -11
  377. package/build/globalOptions.js.map +1 -1
  378. package/build/observability/events/registry.d.ts +67 -1
  379. package/build/observability/events/registry.d.ts.map +1 -1
  380. package/build/observability/events/registry.js +67 -1
  381. package/build/observability/events/registry.js.map +1 -1
  382. package/build/observability/privacy/fields.d.ts +4 -0
  383. package/build/observability/privacy/fields.d.ts.map +1 -1
  384. package/build/observability/privacy/fields.js +4 -0
  385. package/build/observability/privacy/fields.js.map +1 -1
  386. package/build/sdk/legacy/client/runtime/backendDispatchLifetime.d.ts.map +1 -1
  387. package/build/sdk/legacy/client/runtime/backendDispatchLifetime.js +8 -2
  388. package/build/sdk/legacy/client/runtime/backendDispatchLifetime.js.map +1 -1
  389. package/build/sdk/legacy/client/runtime/legacyTransport.d.ts +2 -0
  390. package/build/sdk/legacy/client/runtime/legacyTransport.d.ts.map +1 -1
  391. package/build/sdk/legacy/client/runtime/serveClient.d.ts +6 -1
  392. package/build/sdk/legacy/client/runtime/serveClient.d.ts.map +1 -1
  393. package/build/sdk/legacy/client/runtime/serveClient.js +16 -5
  394. package/build/sdk/legacy/client/runtime/serveClient.js.map +1 -1
  395. package/build/sdk/legacy/commands/serve.d.ts.map +1 -1
  396. package/build/sdk/legacy/commands/serve.js +73 -4
  397. package/build/sdk/legacy/commands/serve.js.map +1 -1
  398. package/build/sdk/legacy/server/protocol/projectAdmission.d.ts +4 -0
  399. package/build/sdk/legacy/server/protocol/projectAdmission.d.ts.map +1 -0
  400. package/build/sdk/legacy/server/protocol/projectAdmission.js +24 -0
  401. package/build/sdk/legacy/server/protocol/projectAdmission.js.map +1 -0
  402. package/build/sdk/legacy/server/protocol/promptRequestHandlers.d.ts.map +1 -1
  403. package/build/sdk/legacy/server/protocol/promptRequestHandlers.js +6 -3
  404. package/build/sdk/legacy/server/protocol/promptRequestHandlers.js.map +1 -1
  405. package/build/sdk/legacy/server/protocol/resourceRequestHandlers.d.ts.map +1 -1
  406. package/build/sdk/legacy/server/protocol/resourceRequestHandlers.js +6 -4
  407. package/build/sdk/legacy/server/protocol/resourceRequestHandlers.js.map +1 -1
  408. package/build/sdk/legacy/server/protocol/resourceSubscriptions.d.ts +1 -1
  409. package/build/sdk/legacy/server/protocol/resourceSubscriptions.d.ts.map +1 -1
  410. package/build/sdk/legacy/server/protocol/resourceSubscriptions.js +193 -41
  411. package/build/sdk/legacy/server/protocol/resourceSubscriptions.js.map +1 -1
  412. package/build/sdk/legacy/server/protocol/toolRequestHandlers.d.ts.map +1 -1
  413. package/build/sdk/legacy/server/protocol/toolRequestHandlers.js +93 -17
  414. package/build/sdk/legacy/server/protocol/toolRequestHandlers.js.map +1 -1
  415. package/build/sdk/legacy/server/runtime/clientInstancePool.d.ts +12 -0
  416. package/build/sdk/legacy/server/runtime/clientInstancePool.d.ts.map +1 -1
  417. package/build/sdk/legacy/server/runtime/clientInstancePool.js +117 -4
  418. package/build/sdk/legacy/server/runtime/clientInstancePool.js.map +1 -1
  419. package/build/sdk/legacy/server/runtime/connectionManager.d.ts.map +1 -1
  420. package/build/sdk/legacy/server/runtime/connectionManager.js +2 -0
  421. package/build/sdk/legacy/server/runtime/connectionManager.js.map +1 -1
  422. package/build/sdk/legacy/server/runtime/requestContextPreparation.d.ts +19 -1
  423. package/build/sdk/legacy/server/runtime/requestContextPreparation.d.ts.map +1 -1
  424. package/build/sdk/legacy/server/runtime/requestContextPreparation.js +40 -7
  425. package/build/sdk/legacy/server/runtime/requestContextPreparation.js.map +1 -1
  426. package/build/sdk/legacy/server/runtime/serverManager.d.ts +6 -2
  427. package/build/sdk/legacy/server/runtime/serverManager.d.ts.map +1 -1
  428. package/build/sdk/legacy/server/runtime/serverManager.js +85 -17
  429. package/build/sdk/legacy/server/runtime/serverManager.js.map +1 -1
  430. package/build/sdk/legacy/server/runtime/templateServerManager.d.ts +26 -4
  431. package/build/sdk/legacy/server/runtime/templateServerManager.d.ts.map +1 -1
  432. package/build/sdk/legacy/server/runtime/templateServerManager.js +260 -14
  433. package/build/sdk/legacy/server/runtime/templateServerManager.js.map +1 -1
  434. package/build/sdk/legacy/transport/http/modernInboundLegacyBridge.js +1 -1
  435. package/build/sdk/legacy/transport/http/modernInboundLegacyBridge.js.map +1 -1
  436. package/build/sdk/legacy/transport/http/streamableSessionLifecycle.d.ts.map +1 -1
  437. package/build/sdk/legacy/transport/http/streamableSessionLifecycle.js +14 -3
  438. package/build/sdk/legacy/transport/http/streamableSessionLifecycle.js.map +1 -1
  439. package/build/sdk/legacy/transport/stdioProxyTransport.d.ts +1 -0
  440. package/build/sdk/legacy/transport/stdioProxyTransport.d.ts.map +1 -1
  441. package/build/sdk/legacy/transport/stdioProxyTransport.js +2 -0
  442. package/build/sdk/legacy/transport/stdioProxyTransport.js.map +1 -1
  443. package/build/template/handlebarsTemplateRenderer.d.ts.map +1 -1
  444. package/build/template/handlebarsTemplateRenderer.js +3 -0
  445. package/build/template/handlebarsTemplateRenderer.js.map +1 -1
  446. package/build/transport/http/middlewares/projectAdmission.d.ts +5 -0
  447. package/build/transport/http/middlewares/projectAdmission.d.ts.map +1 -0
  448. package/build/transport/http/middlewares/projectAdmission.js +33 -0
  449. package/build/transport/http/middlewares/projectAdmission.js.map +1 -0
  450. package/build/transport/http/routes/apiRoutes.d.ts.map +1 -1
  451. package/build/transport/http/routes/apiRoutes.js +4 -0
  452. package/build/transport/http/routes/apiRoutes.js.map +1 -1
  453. package/build/transport/http/routes/inspectHelpers.d.ts +1 -0
  454. package/build/transport/http/routes/inspectHelpers.d.ts.map +1 -1
  455. package/build/transport/http/routes/inspectHelpers.js +2 -0
  456. package/build/transport/http/routes/inspectHelpers.js.map +1 -1
  457. package/build/transport/http/routes/inspectRequestContext.d.ts +5 -2
  458. package/build/transport/http/routes/inspectRequestContext.d.ts.map +1 -1
  459. package/build/transport/http/routes/inspectRequestContext.js +41 -19
  460. package/build/transport/http/routes/inspectRequestContext.js.map +1 -1
  461. package/build/transport/http/routes/inspectRoutes.d.ts +11 -2
  462. package/build/transport/http/routes/inspectRoutes.d.ts.map +1 -1
  463. package/build/transport/http/routes/inspectRoutes.js +94 -24
  464. package/build/transport/http/routes/inspectRoutes.js.map +1 -1
  465. package/build/transport/http/routes/instructionsRoutes.d.ts.map +1 -1
  466. package/build/transport/http/routes/instructionsRoutes.js +20 -8
  467. package/build/transport/http/routes/instructionsRoutes.js.map +1 -1
  468. package/build/transport/http/routes/modernHttpRoutes.d.ts.map +1 -1
  469. package/build/transport/http/routes/modernHttpRoutes.js +96 -13
  470. package/build/transport/http/routes/modernHttpRoutes.js.map +1 -1
  471. package/build/transport/http/routes/modernInteractionBinding.d.ts.map +1 -1
  472. package/build/transport/http/routes/modernInteractionBinding.js +3 -9
  473. package/build/transport/http/routes/modernInteractionBinding.js.map +1 -1
  474. package/build/transport/http/routes/modernSubscriptions.d.ts.map +1 -1
  475. package/build/transport/http/routes/modernSubscriptions.js +7 -5
  476. package/build/transport/http/routes/modernSubscriptions.js.map +1 -1
  477. package/build/transport/http/routes/modernTemplateContext.d.ts +2 -1
  478. package/build/transport/http/routes/modernTemplateContext.d.ts.map +1 -1
  479. package/build/transport/http/routes/modernTemplateContext.js +14 -3
  480. package/build/transport/http/routes/modernTemplateContext.js.map +1 -1
  481. package/build/transport/http/routes/modernToolHeaderRegistry.d.ts.map +1 -1
  482. package/build/transport/http/routes/modernToolHeaderRegistry.js +2 -2
  483. package/build/transport/http/routes/modernToolHeaderRegistry.js.map +1 -1
  484. package/build/transport/http/routes/preparationRoutes.d.ts +26 -0
  485. package/build/transport/http/routes/preparationRoutes.d.ts.map +1 -0
  486. package/build/transport/http/routes/preparationRoutes.js +132 -0
  487. package/build/transport/http/routes/preparationRoutes.js.map +1 -0
  488. package/build/transport/http/routes/projectRoutes.d.ts +18 -0
  489. package/build/transport/http/routes/projectRoutes.d.ts.map +1 -0
  490. package/build/transport/http/routes/projectRoutes.js +159 -0
  491. package/build/transport/http/routes/projectRoutes.js.map +1 -0
  492. package/build/transport/http/routes/streamableHttpRoutes.d.ts.map +1 -1
  493. package/build/transport/http/routes/streamableHttpRoutes.js +24 -4
  494. package/build/transport/http/routes/streamableHttpRoutes.js.map +1 -1
  495. package/build/transport/http/routes/toolRoutes.d.ts.map +1 -1
  496. package/build/transport/http/routes/toolRoutes.js +163 -20
  497. package/build/transport/http/routes/toolRoutes.js.map +1 -1
  498. package/build/transport/http/utils/contextExtractor.d.ts +2 -0
  499. package/build/transport/http/utils/contextExtractor.d.ts.map +1 -1
  500. package/build/transport/http/utils/contextExtractor.js +11 -0
  501. package/build/transport/http/utils/contextExtractor.js.map +1 -1
  502. package/build/transport/http/utils/templateContextAuthority.d.ts +2 -0
  503. package/build/transport/http/utils/templateContextAuthority.d.ts.map +1 -1
  504. package/build/transport/http/utils/templateContextAuthority.js +23 -2
  505. package/build/transport/http/utils/templateContextAuthority.js.map +1 -1
  506. package/build/types/context.d.ts +13 -0
  507. package/build/types/context.d.ts.map +1 -1
  508. package/build/types/context.js.map +1 -1
  509. package/build/utils/cli/help.d.ts +7 -0
  510. package/build/utils/cli/help.d.ts.map +1 -0
  511. package/build/utils/cli/help.js +57 -0
  512. package/build/utils/cli/help.js.map +1 -0
  513. package/package.json +20 -22
  514. package/build/admin/assets/admin-icons-CYGTDZA5.js +0 -1
  515. package/build/admin/assets/admin-vendor-62eL-qdH.js +0 -1
  516. package/build/admin/assets/admin-vendor-BbMrl7MK.js +0 -3
  517. package/build/admin/assets/admin-vendor-DpjVwd81.js +0 -62
@@ -0,0 +1,885 @@
1
+ import { createHash, randomUUID } from 'node:crypto';
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import { canonicalLifecyclePath, getProjectLifecycle } from './projectLifecycle.js';
5
+ import { ConfigManager } from '../config/configManager.js';
6
+ import { normalizeTags, resolveProjectContext } from '../config/projectConfigLoader.js';
7
+ import { invalidatePreparedToolProvider } from '../core/capabilities/capabilityPagination.js';
8
+ import { readConfiguredToolSnapshot } from '../core/capabilities/configuredToolSnapshot.js';
9
+ import { validateProjectPreparationAuthority } from '../core/context/projectPreparationAuthority.js';
10
+ import { resolveFilterSelection } from '../core/filtering/filterSelection.js';
11
+ import { TemplateFilteringService } from '../core/filtering/templateFilteringService.js';
12
+ import { AgentConfigManager } from '../core/server/agentConfig.js';
13
+ import { createConnectionResolver } from '../core/server/connectionResolver.js';
14
+ import { PreparationAdapterRegistry } from '../domains/backend-preparation/adapterRegistry.js';
15
+ import { ConfiguredCommandPreparationAdapter } from '../domains/backend-preparation/configuredCommandAdapter.js';
16
+ import { PreparationConfigurationError, validatePreparationConfig, } from '../domains/backend-preparation/integrationDefinitions.js';
17
+ import { BackendPolicySchema, preparationKey, PreparationTargetSchema, } from '../domains/backend-preparation/policy.js';
18
+ import { BackendPreparationService } from '../domains/backend-preparation/service.js';
19
+ import { PresetManager } from '../domains/preset/manager/presetManager.js';
20
+ import { hasExplicitProjectFilterSelection } from '../domains/project-selection/projectPolicy.js';
21
+ import { requireProjectTarget } from '../domains/project-selection/projectSelection.js';
22
+ import { assertOwnerOnlyDirPermissions, enforceOwnerOnlyFilePermissions, openCredentialReadSync, } from '../utils/filePermissions.js';
23
+ import { z } from 'zod';
24
+ export class PreparationAuthorizationChangedError extends Error {
25
+ constructor() {
26
+ super('Preparation authorization changed');
27
+ }
28
+ }
29
+ const failureSchema = z
30
+ .object({
31
+ code: z.string().max(256),
32
+ message: z.string().max(4096),
33
+ retryable: z.boolean(),
34
+ instructions: z.string().max(8192),
35
+ })
36
+ .strict();
37
+ const savedSchema = z
38
+ .object({
39
+ key: z.string().length(64),
40
+ target: PreparationTargetSchema.extend({
41
+ checkoutRoot: z.string().min(1).max(8192),
42
+ backendName: z.string().min(1).max(256),
43
+ backendIdentity: z.string().min(1).max(128),
44
+ configurationKey: z.string().min(1).max(128),
45
+ }),
46
+ operation: z.string().min(1).max(256),
47
+ policy: BackendPolicySchema,
48
+ action: z.enum(['initialize', 'sync', 'rebuild', 'install', 'paid']),
49
+ state: z.enum(['queued', 'running', 'cancelling', 'ready', 'not_ready', 'failed', 'cancelled']),
50
+ previousJobId: z.string().min(1).max(256),
51
+ failure: failureSchema.optional(),
52
+ })
53
+ .strict();
54
+ /** Only advisory operation data is persisted. No PID or saved flag can authorize process control. */
55
+ class PreparationSnapshotStore {
56
+ file;
57
+ capacity;
58
+ records = new Map();
59
+ reservations = new Map();
60
+ static maximumBytes = 128 * 1024 * 1024;
61
+ constructor(file, capacity) {
62
+ this.file = file;
63
+ this.capacity = capacity;
64
+ if (!file)
65
+ return;
66
+ if (!fs.existsSync(file))
67
+ return;
68
+ assertOwnerOnlyDirPermissions(path.dirname(file));
69
+ const fd = openCredentialReadSync(file);
70
+ try {
71
+ enforceOwnerOnlyFilePermissions(fd, file);
72
+ const stat = fs.fstatSync(fd);
73
+ if (!stat.isFile() || stat.size > PreparationSnapshotStore.maximumBytes)
74
+ throw new Error('Invalid preparation recovery storage');
75
+ const records = z
76
+ .array(savedSchema)
77
+ .max(capacity)
78
+ .parse(JSON.parse(fs.readFileSync(fd, 'utf8')));
79
+ for (const record of records)
80
+ this.records.set(record.key, record);
81
+ }
82
+ finally {
83
+ fs.closeSync(fd);
84
+ }
85
+ }
86
+ get(key) {
87
+ return this.records.get(key);
88
+ }
89
+ assertCapacity(key) {
90
+ if (!this.file || this.records.has(key) || this.reservations.has(key))
91
+ return;
92
+ const size = new Set([...this.records.keys(), ...this.reservations.keys()]).size;
93
+ // Reserve a bounded worst-case advisory record before admitting work, including UTF-8 text.
94
+ if (size >= this.capacity || (size + 1) * 96 * 1024 > PreparationSnapshotStore.maximumBytes)
95
+ throw new Error('Preparation recovery storage is full');
96
+ }
97
+ reserve(key) {
98
+ this.assertCapacity(key);
99
+ this.reservations.set(key, (this.reservations.get(key) ?? 0) + 1);
100
+ return () => {
101
+ const remaining = (this.reservations.get(key) ?? 1) - 1;
102
+ if (remaining === 0)
103
+ this.reservations.delete(key);
104
+ else
105
+ this.reservations.set(key, remaining);
106
+ };
107
+ }
108
+ save(key, status, policy) {
109
+ if (!this.file)
110
+ return;
111
+ if (status.state === 'ready' || status.state === 'cancelled') {
112
+ this.delete(key);
113
+ return;
114
+ }
115
+ this.assertCapacity(key);
116
+ // Persist only a bounded advisory copy. Restart imports also require instructions <= 4096.
117
+ const failure = status.failure && {
118
+ ...status.failure,
119
+ code: status.failure.code.slice(0, 256),
120
+ message: status.failure.message.slice(0, 4096),
121
+ instructions: status.failure.instructions.slice(0, 4096),
122
+ };
123
+ this.records.set(key, savedSchema.parse({
124
+ key,
125
+ target: status.target,
126
+ operation: status.operation,
127
+ policy: { ...policy, executionDeadlineMs: status.executionDeadlineMs },
128
+ action: status.action,
129
+ state: status.state,
130
+ previousJobId: status.id,
131
+ failure,
132
+ }));
133
+ this.flush();
134
+ }
135
+ delete(key) {
136
+ if (this.records.delete(key))
137
+ this.flush();
138
+ }
139
+ flush() {
140
+ if (!this.file)
141
+ return;
142
+ const directory = path.dirname(this.file);
143
+ fs.mkdirSync(directory, { recursive: true, mode: 0o700 });
144
+ assertOwnerOnlyDirPermissions(directory);
145
+ const temporary = `${this.file}.${randomUUID()}.tmp`;
146
+ try {
147
+ fs.writeFileSync(temporary, JSON.stringify([...this.records.values()]), { flag: 'wx', mode: 0o600 });
148
+ fs.renameSync(temporary, this.file);
149
+ }
150
+ finally {
151
+ if (fs.existsSync(temporary))
152
+ fs.unlinkSync(temporary);
153
+ }
154
+ }
155
+ }
156
+ function digest(value) {
157
+ return createHash('sha256').update(JSON.stringify(value)).digest('hex');
158
+ }
159
+ /** One coordinator and scheduler per Aggregated Runtime, independent of advertised tools. */
160
+ export class BackendPreparationCoordinator {
161
+ ports;
162
+ grantInputs = new WeakMap();
163
+ namedGrants = new WeakSet();
164
+ service;
165
+ registry = new PreparationAdapterRegistry();
166
+ adapters = new Map();
167
+ registered = new Set();
168
+ handles = new Map();
169
+ monitored = new Set();
170
+ refreshedJobs = new Set();
171
+ readinessRefreshes = new Map();
172
+ latestAdapters = new Map();
173
+ adapterCalls = new Map();
174
+ failureAdapters = new WeakMap();
175
+ disposing = new Set();
176
+ disposalFailures = [];
177
+ store;
178
+ closed = false;
179
+ shutdownPromise;
180
+ constructor(ports = {}) {
181
+ this.ports = ports;
182
+ this.service = new BackendPreparationService(this.registry, ports.options);
183
+ this.store = new PreparationSnapshotStore(ports.storagePath ? path.join(ports.storagePath, 'backend-preparation.json') : undefined, this.service.options.maxRecords);
184
+ }
185
+ /** Caller must authorize the target context before this function performs any filesystem access. */
186
+ async resolveGrant(input) {
187
+ if (this.closed)
188
+ throw new Error('Preparation coordinator is stopped');
189
+ // Live inbound connections also carry SDK adapters and notification callbacks.
190
+ // Capture only the selector data used by preparation, before any asynchronous reads.
191
+ const filter = input.filterConfig;
192
+ input = {
193
+ backendName: input.backendName,
194
+ checkoutPath: input.checkoutPath,
195
+ owner: input.owner,
196
+ filterConfig: structuredClone({
197
+ tags: filter.tags,
198
+ tagExpression: filter.tagExpression,
199
+ tagQuery: filter.tagQuery,
200
+ tagFilterMode: filter.tagFilterMode,
201
+ presetName: filter.presetName,
202
+ projectFilterMode: filter.projectFilterMode,
203
+ }),
204
+ };
205
+ const declared = ConfigManager.getInstance().loadDeclaredServerConfigs();
206
+ if (declared.errors.length)
207
+ throw new Error('Runtime backend configuration is unavailable');
208
+ const definition = declared.templateServers[input.backendName] ?? declared.staticServers[input.backendName];
209
+ if (!definition || definition.disabled)
210
+ throw new Error('Backend is unavailable for this selection');
211
+ if (TemplateFilteringService.getMatchingTemplates([[input.backendName, definition]], input.filterConfig).length !== 1)
212
+ throw new Error('Backend is unavailable for this selection');
213
+ // Runtime-owned settings are read from the unrendered definition. Context cannot interpolate executable or permissions.
214
+ const config = definition.preparation ? validatePreparationConfig(definition.preparation) : undefined;
215
+ const backendIdentity = digest(definition);
216
+ const checkoutRoot = await fs.promises.realpath(input.checkoutPath);
217
+ if (!(await fs.promises.stat(checkoutRoot)).isDirectory())
218
+ throw new Error('Project Checkout is not a directory');
219
+ const { projectConfig } = await resolveProjectContext(checkoutRoot);
220
+ if (!hasExplicitProjectFilterSelection(input.filterConfig)) {
221
+ let projectDefaults = {};
222
+ if (projectConfig?.preset !== undefined)
223
+ projectDefaults = { preset: projectConfig.preset };
224
+ else if (projectConfig?.filter !== undefined)
225
+ projectDefaults = { filter: projectConfig.filter };
226
+ else if (projectConfig?.tags !== undefined)
227
+ projectDefaults = { tags: normalizeTags(projectConfig.tags)?.join(',') };
228
+ const projectFilter = resolveFilterSelection(projectDefaults, {
229
+ presetLookup: { getPreset: (name) => PresetManager.getInstance().getPreset(name) ?? undefined },
230
+ });
231
+ if (!projectFilter.ok)
232
+ throw new Error('Project filter configuration is invalid');
233
+ if (TemplateFilteringService.getMatchingTemplates([[input.backendName, definition]], projectFilter.selection.compatibility).length !== 1)
234
+ throw new Error('Backend is unavailable for this checkout');
235
+ }
236
+ const configurationKey = digest(config ?? { unsupported: true });
237
+ if (config?.integration)
238
+ this.register(input.backendName, configurationKey, config);
239
+ const preferences = structuredClone(projectConfig?.preparation ?? {});
240
+ if (config?.activation === 'setup') {
241
+ if (preferences[input.backendName] === undefined)
242
+ preferences[input.backendName] = { enabled: true };
243
+ }
244
+ if (config?.enabled === false)
245
+ preferences[input.backendName] = { enabled: false };
246
+ let allowedActions = config?.allowedActions ?? [];
247
+ if (config?.enabled === false)
248
+ allowedActions = [];
249
+ if (config?.definition && preferences[input.backendName]?.enabled === false)
250
+ allowedActions = [];
251
+ const grant = {
252
+ owner: input.owner,
253
+ integrationAvailable: Boolean(config?.integration),
254
+ target: { checkoutRoot, backendName: input.backendName, backendIdentity, configurationKey },
255
+ policy: config
256
+ ? {
257
+ allowedActions,
258
+ executionDeadlineMs: config.executionDeadlineMs,
259
+ transientRetryLimit: config.transientRetryLimit,
260
+ }
261
+ : { allowedActions: [] },
262
+ preferences,
263
+ };
264
+ if (config?.definition)
265
+ this.namedGrants.add(grant);
266
+ this.grantInputs.set(grant, structuredClone(input));
267
+ return grant;
268
+ }
269
+ async control(grant, request) {
270
+ if (['wait', 'cancel'].includes(request.action) && !request.id)
271
+ throw new Error('This action requires a job id');
272
+ if (request.action === 'inspect' && request.id)
273
+ throw new Error('inspect does not accept a job id');
274
+ if (request.action === 'prepare' || request.action === 'retry')
275
+ getProjectLifecycle()?.assertScheduling([grant.target.checkoutRoot]);
276
+ if (this.closed)
277
+ throw new Error('Preparation coordinator is stopped');
278
+ if (!request.id)
279
+ this.assertNamedGrantCurrent(grant);
280
+ if (grant.integrationAvailable === false)
281
+ return {
282
+ state: 'unsupported',
283
+ instructions: 'No configured preparation integration is available for this backend.',
284
+ };
285
+ const requestedHandle = request.id ? this.handles.get(request.id) : undefined;
286
+ const operation = request.operation ??
287
+ (requestedHandle ? this.service.status(requestedHandle.serviceId)?.operation : undefined) ??
288
+ 'query';
289
+ const expiresAt = Date.now() + (request.waitMs ?? this.service.options.requestWaitMs);
290
+ const probeOptions = () => ({ waitMs: Math.max(0, expiresAt - Date.now()), signal: request.signal });
291
+ const validateAdmission = () => this.revalidateGrant(grant, request.validateAdmission, false, expiresAt, request.signal);
292
+ const key = digest(preparationKey(grant.target, grant.policy, this.service.options, operation));
293
+ // Draining controls inspect cached job state without launching native probes in the checkout.
294
+ if (getProjectLifecycle()?.status(grant.target.checkoutRoot).admission === 'draining') {
295
+ const handle = request.id ? this.handles.get(request.id) : undefined;
296
+ if (request.id && (!handle || handle.owner !== grant.owner || handle.key !== key))
297
+ throw new Error('Unknown preparation operation for this grant and checkout');
298
+ let status = handle ? this.service.status(handle.serviceId) : this.currentStatus(key);
299
+ if (!status)
300
+ return { state: 'conflict', instructions: 'Project Checkout is draining; resume before native inspection.' };
301
+ if (request.action === 'cancel')
302
+ status = this.service.cancel(handle.serviceId);
303
+ if (request.action === 'wait')
304
+ status = await this.service.wait(handle.serviceId, probeOptions());
305
+ return status ? this.presentStatus(grant, key, status) : undefined;
306
+ }
307
+ if (request.action === 'inspect') {
308
+ if (request.id)
309
+ throw new Error('inspect does not accept a job id');
310
+ const current = this.currentStatus(key);
311
+ const saved = this.store.get(key);
312
+ const readiness = saved && !current
313
+ ? await this.service.recover(grant.target, operation, {
314
+ previousJobId: saved.previousJobId,
315
+ previousState: saved.state,
316
+ }, probeOptions())
317
+ : await this.service.inspect(grant.target, operation, probeOptions());
318
+ this.assertNamedGrantCurrent(grant);
319
+ if (!current)
320
+ return readiness;
321
+ const progress = await this.service.inspectProgress(grant.target, operation, probeOptions());
322
+ this.assertNamedGrantCurrent(grant);
323
+ return { state: 'job', status: this.presentStatus(grant, key, { ...current, readiness, progress }) };
324
+ }
325
+ if (!request.id) {
326
+ const current = this.currentStatus(key);
327
+ if (current) {
328
+ if (request.action === 'status' &&
329
+ ['queued', 'running', 'cancelling'].includes(current.state) &&
330
+ current.operation === operation)
331
+ return this.publishStatus(grant, key, current);
332
+ if (request.action === 'retry') {
333
+ return this.withReservation(key, async (beforeAdmission) => this.publish(grant, key, await this.service.retry(current.id, grant.policy, {
334
+ ...probeOptions(),
335
+ beforeAdmission,
336
+ validateAdmission,
337
+ })), grant, request.assertAdmission);
338
+ }
339
+ if (request.action === 'prepare' && current.state !== 'ready')
340
+ return this.publish(grant, key, { state: 'job', status: current });
341
+ }
342
+ }
343
+ if (request.id) {
344
+ const handle = this.handles.get(request.id);
345
+ if (!handle || handle.owner !== grant.owner || handle.key !== key)
346
+ throw new Error('Unknown preparation operation for this grant and checkout');
347
+ if (request.action === 'cancel')
348
+ return this.publishStatus(grant, key, this.service.cancel(handle.serviceId));
349
+ if (request.action === 'retry') {
350
+ return this.withReservation(key, async (beforeAdmission) => this.publish(grant, key, await this.service.retry(handle.serviceId, grant.policy, {
351
+ ...probeOptions(),
352
+ beforeAdmission,
353
+ validateAdmission,
354
+ })), grant, request.assertAdmission);
355
+ }
356
+ if (request.action === 'wait' || request.action === 'status') {
357
+ const status = request.action === 'wait'
358
+ ? await this.service.wait(handle.serviceId, { waitMs: request.waitMs, signal: request.signal })
359
+ : this.service.status(handle.serviceId);
360
+ if (status?.state === 'ready')
361
+ await this.refreshReadyStatus(status);
362
+ return this.publishStatus(grant, key, status);
363
+ }
364
+ throw new Error('Job id is not accepted for this action');
365
+ }
366
+ const saved = this.store.get(key);
367
+ if (saved) {
368
+ const readiness = await this.service.recover(grant.target, operation, {
369
+ previousJobId: saved.previousJobId,
370
+ previousState: saved.state,
371
+ }, probeOptions());
372
+ this.assertNamedGrantCurrent(grant);
373
+ if (readiness.state === 'ready') {
374
+ this.service.clearResolvedFailure(grant.target, operation, grant.policy, readiness);
375
+ this.recycle();
376
+ if (saved.operation === operation)
377
+ this.store.delete(key);
378
+ return { state: 'ready', readiness };
379
+ }
380
+ if (['failed', 'not_ready'].includes(saved.state) && saved.failure) {
381
+ const restored = this.service.importFailure(grant.target, saved.operation, { ...grant.policy, executionDeadlineMs: saved.policy.executionDeadlineMs }, saved.action, saved.failure, saved.state === 'not_ready' ? 'not_ready' : 'failed') ?? this.currentStatus(key);
382
+ if (restored) {
383
+ if (request.action === 'retry')
384
+ return this.withReservation(key, async (beforeAdmission) => this.publish(grant, key, await this.service.retry(restored.id, grant.policy, {
385
+ ...probeOptions(),
386
+ beforeAdmission,
387
+ validateAdmission,
388
+ })), grant, request.assertAdmission);
389
+ return this.publish(grant, key, { state: 'job', status: restored });
390
+ }
391
+ }
392
+ if (readiness.state !== 'required')
393
+ return readiness;
394
+ if (request.action === 'status')
395
+ return readiness;
396
+ if (request.action === 'retry')
397
+ this.store.delete(key);
398
+ }
399
+ if (request.action === 'status') {
400
+ const readiness = await this.service.inspect(grant.target, operation, probeOptions());
401
+ this.assertNamedGrantCurrent(grant);
402
+ if (readiness.state === 'ready') {
403
+ this.service.clearResolvedFailure(grant.target, operation, grant.policy, readiness);
404
+ this.recycle();
405
+ const saved = this.store.get(key);
406
+ if (saved?.operation === operation)
407
+ this.store.delete(key);
408
+ }
409
+ return readiness;
410
+ }
411
+ if (request.action !== 'prepare' && request.action !== 'retry')
412
+ throw new Error('This action requires a preparation operation id');
413
+ return this.withReservation(key, async (beforeAdmission) => this.publish(grant, key, await this.service.prepare(grant.target, operation, grant.policy, undefined, {
414
+ ...probeOptions(),
415
+ beforeAdmission,
416
+ validateAdmission,
417
+ })), grant, request.assertAdmission);
418
+ }
419
+ async admit(grant, operation, options = {}) {
420
+ if (this.closed)
421
+ throw new Error('Preparation coordinator is stopped');
422
+ this.assertNamedGrantCurrent(grant);
423
+ if (grant.integrationAvailable === false)
424
+ return {
425
+ state: 'unsupported',
426
+ instructions: 'No configured preparation integration is available for this backend.',
427
+ };
428
+ const expiresAt = Date.now() + (options.waitMs ?? this.service.options.requestWaitMs);
429
+ const key = digest(preparationKey(grant.target, grant.policy, this.service.options, operation));
430
+ const recovered = this.store.get(key);
431
+ if (recovered && !this.currentStatus(key)) {
432
+ const status = await this.control(grant, {
433
+ action: 'status',
434
+ operation,
435
+ waitMs: Math.max(0, expiresAt - Date.now()),
436
+ signal: options.signal,
437
+ });
438
+ if (!status)
439
+ throw new Error('Preparation recovery status is unavailable');
440
+ if (status.state === 'ready' && 'readiness' in status && status.readiness?.state === 'ready') {
441
+ if (!('operation' in status) || status.operation === operation) {
442
+ this.assertNamedGrantCurrent(grant);
443
+ return { state: 'ready', readiness: status.readiness };
444
+ }
445
+ }
446
+ if (this.store.get(recovered.key)) {
447
+ if ('id' in status)
448
+ return { state: 'job', status };
449
+ return status;
450
+ }
451
+ }
452
+ return this.withReservation(key, async (beforeAdmission) => {
453
+ const result = await this.service.admit(grant.target, operation, grant.policy, grant.preferences, {
454
+ ...options,
455
+ waitMs: Math.max(0, expiresAt - Date.now()),
456
+ beforeAdmission,
457
+ validateAdmission: () => this.revalidateGrant(grant, options.validateAdmission, true, expiresAt, options.signal),
458
+ });
459
+ if (result.state === 'ready') {
460
+ this.assertNamedGrantCurrent(grant);
461
+ const current = this.currentStatus(key);
462
+ if (current?.state === 'ready')
463
+ await this.refreshReadyStatus(current);
464
+ const saved = this.store.get(key);
465
+ if (saved?.operation === operation)
466
+ this.store.delete(key);
467
+ this.recycle();
468
+ this.assertNamedGrantCurrent(grant);
469
+ return result;
470
+ }
471
+ if (result.state === 'pending')
472
+ return { ...result, status: this.publishStatus(grant, key, result.status) };
473
+ return this.publish(grant, key, result);
474
+ }, grant, options.assertAdmission);
475
+ }
476
+ getProjectBlockers(checkout) {
477
+ const canonical = canonicalLifecyclePath(checkout);
478
+ const blockers = [];
479
+ for (const status of this.service.activeStatuses()) {
480
+ if (status.target.checkoutRoot === canonical)
481
+ blockers.push({ kind: 'preparation-job', id: status.id });
482
+ }
483
+ return blockers;
484
+ }
485
+ async withReservation(key, action, grant, assertAdmission) {
486
+ let release;
487
+ try {
488
+ return await action(() => {
489
+ this.assertGrantCurrent(grant);
490
+ getProjectLifecycle()?.assertScheduling([grant.target.checkoutRoot]);
491
+ assertAdmission?.();
492
+ release ??= this.store.reserve(key);
493
+ });
494
+ }
495
+ finally {
496
+ release?.();
497
+ }
498
+ }
499
+ assertNamedGrantCurrent(grant) {
500
+ if (!this.namedGrants.has(grant))
501
+ return;
502
+ try {
503
+ this.assertGrantCurrent(grant);
504
+ }
505
+ catch {
506
+ throw new PreparationAuthorizationChangedError();
507
+ }
508
+ }
509
+ assertGrantCurrent(grant) {
510
+ const input = this.grantInputs.get(grant);
511
+ const current = ConfigManager.getInstance().loadDeclaredServerConfigs();
512
+ const definition = current.templateServers[grant.target.backendName] ?? current.staticServers[grant.target.backendName];
513
+ let configurationKey;
514
+ try {
515
+ configurationKey = definition?.preparation
516
+ ? digest(validatePreparationConfig(definition.preparation))
517
+ : digest({ unsupported: true });
518
+ }
519
+ catch (error) {
520
+ if (error instanceof PreparationConfigurationError)
521
+ throw new PreparationAuthorizationChangedError();
522
+ throw error;
523
+ }
524
+ if (configurationKey !== grant.target.configurationKey ||
525
+ !input ||
526
+ current.errors.length ||
527
+ !definition ||
528
+ definition.disabled ||
529
+ digest(definition) !== grant.target.backendIdentity ||
530
+ TemplateFilteringService.getMatchingTemplates([[grant.target.backendName, definition]], input.filterConfig)
531
+ .length !== 1)
532
+ throw new PreparationAuthorizationChangedError();
533
+ }
534
+ async revalidateGrant(grant, validate, automatic, expiresAt, signal) {
535
+ const input = this.grantInputs.get(grant);
536
+ if (!input || signal?.aborted || Date.now() >= expiresAt)
537
+ throw new PreparationAuthorizationChangedError();
538
+ let timer;
539
+ let abort = () => undefined;
540
+ const stopped = new Promise((_, reject) => {
541
+ abort = () => reject(new PreparationAuthorizationChangedError());
542
+ timer = setTimeout(abort, Math.max(0, expiresAt - Date.now()));
543
+ signal?.addEventListener('abort', abort, { once: true });
544
+ });
545
+ try {
546
+ await Promise.race([
547
+ stopped,
548
+ (async () => {
549
+ if (validate && !(await validate()))
550
+ throw new PreparationAuthorizationChangedError();
551
+ let fresh;
552
+ try {
553
+ fresh = await this.resolveGrant(input);
554
+ }
555
+ catch {
556
+ throw new PreparationAuthorizationChangedError();
557
+ }
558
+ if (JSON.stringify(fresh.target) !== JSON.stringify(grant.target) ||
559
+ JSON.stringify(fresh.policy) !== JSON.stringify(grant.policy) ||
560
+ (automatic && !fresh.preferences[grant.target.backendName]?.enabled))
561
+ throw new PreparationAuthorizationChangedError();
562
+ if (validate && !(await validate()))
563
+ throw new PreparationAuthorizationChangedError();
564
+ if (signal?.aborted || Date.now() >= expiresAt)
565
+ throw new PreparationAuthorizationChangedError();
566
+ })(),
567
+ ]);
568
+ }
569
+ finally {
570
+ clearTimeout(timer);
571
+ signal?.removeEventListener('abort', abort);
572
+ }
573
+ }
574
+ shutdown() {
575
+ this.shutdownPromise ??= this.stop();
576
+ return this.shutdownPromise;
577
+ }
578
+ async stop() {
579
+ this.closed = true;
580
+ await this.service.shutdown();
581
+ await Promise.allSettled(this.readinessRefreshes.values());
582
+ await Promise.all([...this.adapters.values()].map(async (adapter) => {
583
+ await adapter.dispose?.();
584
+ }));
585
+ await Promise.all(this.disposing);
586
+ if (this.disposalFailures.length)
587
+ throw new AggregateError(this.disposalFailures, 'Preparation source observer cleanup failed');
588
+ this.handles.clear();
589
+ }
590
+ register(backendName, configurationKey, config) {
591
+ const adapterKey = `${backendName}:${configurationKey}`;
592
+ this.latestAdapters.set(backendName, adapterKey);
593
+ this.recycle();
594
+ if (!this.adapters.has(adapterKey)) {
595
+ if (this.adapters.size >= this.service.options.maxRecords)
596
+ throw new Error('Preparation adapter capacity reached');
597
+ this.adapters.set(adapterKey, this.ports.adapterFactory?.(config) ??
598
+ new ConfiguredCommandPreparationAdapter(config.integration, config.helperSnapshots));
599
+ }
600
+ if (this.registered.has(backendName))
601
+ return;
602
+ const adapterFor = (target) => {
603
+ const adapter = this.adapters.get(`${target.backendName}:${target.configurationKey}`);
604
+ if (!adapter)
605
+ throw new Error('Preparation backend configuration changed');
606
+ return adapter;
607
+ };
608
+ this.registry.register(backendName, {
609
+ inspect: (target, operation, options) => this.trackAdapter(target, () => adapterFor(target).inspect(target, operation, options)),
610
+ prepare: (target, action, options) => this.trackAdapter(target, () => adapterFor(target).prepare(target, action, options)),
611
+ progress: (target, operation, options) => this.trackAdapter(target, () => adapterFor(target).progress?.(target, operation, options) ?? Promise.resolve(undefined)),
612
+ classifyFailure: (error) => {
613
+ const adapter = error !== null && typeof error === 'object' ? this.failureAdapters.get(error) : undefined;
614
+ return (adapter?.classifyFailure(error) ?? {
615
+ code: 'adapter_unavailable',
616
+ message: 'Preparation adapter is unavailable.',
617
+ retryable: false,
618
+ instructions: 'Inspect runtime backend configuration and explicitly retry.',
619
+ });
620
+ },
621
+ reconcile: (target, operation, advisory, options) => this.trackAdapter(target, () => {
622
+ const adapter = adapterFor(target);
623
+ return (adapter.reconcile?.(target, operation, advisory, options) ??
624
+ Promise.resolve({
625
+ state: 'conflict',
626
+ instructions: 'Native recovery is unavailable; reconcile ownership before retrying.',
627
+ }));
628
+ }),
629
+ });
630
+ this.registered.add(backendName);
631
+ }
632
+ publish(grant, key, result) {
633
+ if (result.state === 'ready')
634
+ this.assertNamedGrantCurrent(grant);
635
+ if (result.state === 'pending')
636
+ return { ...result, status: this.publishStatus(grant, key, result.status) };
637
+ if (result.state !== 'job')
638
+ return result;
639
+ return { ...result, status: this.publishStatus(grant, key, result.status) };
640
+ }
641
+ publishStatus(grant, key, status) {
642
+ if (!status)
643
+ return undefined;
644
+ this.recycle();
645
+ this.store.save(key, status, grant.policy);
646
+ this.monitor(grant, key, status);
647
+ return this.presentStatus(grant, key, status);
648
+ }
649
+ presentStatus(grant, key, status) {
650
+ let handle = [...this.handles].find(([, value]) => value.owner === grant.owner && value.key === key && value.serviceId === status.id)?.[0];
651
+ if (!handle) {
652
+ if (this.handles.size >= this.service.options.maxRecords * 4)
653
+ throw new Error('Preparation control capacity reached');
654
+ handle = randomUUID();
655
+ this.handles.set(handle, { owner: grant.owner, key, serviceId: status.id });
656
+ }
657
+ return {
658
+ ...status,
659
+ id: handle,
660
+ target: { checkoutRoot: status.target.checkoutRoot, backendName: status.target.backendName },
661
+ };
662
+ }
663
+ currentStatus(key) {
664
+ for (const value of [...this.handles.values()].reverse()) {
665
+ if (value.key !== key)
666
+ continue;
667
+ const status = this.service.status(value.serviceId);
668
+ if (status)
669
+ return status;
670
+ }
671
+ return undefined;
672
+ }
673
+ async trackAdapter(target, action) {
674
+ const key = `${target.backendName}:${target.configurationKey}`;
675
+ const adapter = this.adapters.get(key);
676
+ this.adapterCalls.set(key, (this.adapterCalls.get(key) ?? 0) + 1);
677
+ try {
678
+ return await action();
679
+ }
680
+ catch (error) {
681
+ const wrapped = error !== null && typeof error === 'object' ? error : new Error(String(error));
682
+ if (adapter)
683
+ this.failureAdapters.set(wrapped, adapter);
684
+ throw wrapped;
685
+ }
686
+ finally {
687
+ this.adapterCalls.set(key, (this.adapterCalls.get(key) ?? 1) - 1);
688
+ }
689
+ }
690
+ recycle() {
691
+ for (const [id, handle] of this.handles) {
692
+ const status = this.service.status(handle.serviceId);
693
+ if (!status) {
694
+ this.handles.delete(id);
695
+ continue;
696
+ }
697
+ if (this.handles.size >= this.service.options.maxRecords * 4 && ['ready', 'cancelled'].includes(status.state))
698
+ this.handles.delete(id);
699
+ }
700
+ for (const [key, adapter] of this.adapters) {
701
+ if ([...this.latestAdapters.values()].includes(key))
702
+ continue;
703
+ if ((this.adapterCalls.get(key) ?? 0) > 0)
704
+ continue;
705
+ const pending = [...this.handles.values()].some((handle) => {
706
+ const status = this.service.status(handle.serviceId);
707
+ if (!status || !['queued', 'running', 'cancelling'].includes(status.state))
708
+ return false;
709
+ return `${status.target.backendName}:${status.target.configurationKey}` === key;
710
+ });
711
+ if (pending)
712
+ continue;
713
+ const disposing = Promise.resolve().then(async () => {
714
+ await adapter.dispose?.();
715
+ });
716
+ this.disposing.add(disposing);
717
+ void disposing.then(() => this.disposing.delete(disposing), (error) => {
718
+ this.disposalFailures.push(error);
719
+ this.disposing.delete(disposing);
720
+ });
721
+ this.adapters.delete(key);
722
+ this.adapterCalls.delete(key);
723
+ }
724
+ }
725
+ monitor(grant, key, status) {
726
+ if (this.monitored.has(status.id))
727
+ return;
728
+ if (['ready', 'not_ready', 'failed', 'cancelled'].includes(status.state))
729
+ return;
730
+ this.monitored.add(status.id);
731
+ void (async () => {
732
+ while (true) {
733
+ const finished = await this.service.wait(status.id, { waitMs: 3_600_000 });
734
+ if (!finished)
735
+ return;
736
+ this.store.save(key, finished, grant.policy);
737
+ if (finished.state === 'ready')
738
+ await this.refreshReadyStatus(finished);
739
+ if (['ready', 'not_ready', 'failed', 'cancelled'].includes(finished.state))
740
+ return;
741
+ }
742
+ })()
743
+ .catch(() => {
744
+ /* Status remains available through explicit controls; no implicit retry. */
745
+ })
746
+ .finally(() => this.monitored.delete(status.id));
747
+ }
748
+ async refreshReadyStatus(status) {
749
+ if (this.refreshedJobs.has(status.id))
750
+ return;
751
+ const existing = this.readinessRefreshes.get(status.id);
752
+ if (existing)
753
+ return existing;
754
+ const refresh = Promise.resolve()
755
+ .then(() => this.ports.onReady?.(status.target))
756
+ .then(() => {
757
+ this.refreshedJobs.add(status.id);
758
+ if (this.refreshedJobs.size > this.service.options.maxRecords)
759
+ this.refreshedJobs.delete(this.refreshedJobs.values().next().value);
760
+ });
761
+ this.readinessRefreshes.set(status.id, refresh);
762
+ try {
763
+ await refresh;
764
+ }
765
+ finally {
766
+ this.readinessRefreshes.delete(status.id);
767
+ }
768
+ }
769
+ }
770
+ const runtimeCoordinators = new WeakMap();
771
+ export async function refreshPreparedBackendCapabilities(serverManager, target, options = {}) {
772
+ const declared = ConfigManager.getInstance().loadDeclaredServerConfigs();
773
+ const definition = declared.templateServers[target.backendName] ?? declared.staticServers[target.backendName];
774
+ if (declared.errors.length || !definition || definition.disabled || digest(definition) !== target.backendIdentity)
775
+ return;
776
+ if (definition.preparation?.definition) {
777
+ try {
778
+ const currentConfigurationKey = digest(validatePreparationConfig(definition.preparation));
779
+ if (currentConfigurationKey !== target.configurationKey)
780
+ return;
781
+ }
782
+ catch (error) {
783
+ if (error instanceof PreparationConfigurationError)
784
+ return;
785
+ throw error;
786
+ }
787
+ }
788
+ const manager = serverManager.getTemplateServerManager();
789
+ const bindingContexts = manager.getBindingContexts();
790
+ const resolver = createConnectionResolver(serverManager.getClients(), {
791
+ getBindingContext: (bindingId) => bindingContexts.get(bindingId),
792
+ getBindingPolicies: (bindingId) => manager.getBindingPolicies(bindingId),
793
+ getRenderedHashForSession: (bindingId, backendName) => manager.getRenderedHashForSession(bindingId, backendName),
794
+ getAllRenderedHashesForSession: (bindingId) => manager.getAllRenderedHashesForSession(bindingId),
795
+ });
796
+ const connections = new Set();
797
+ for (const [bindingId, context] of bindingContexts) {
798
+ const filter = manager.getBindingConfiguration(bindingId);
799
+ if (!filter ||
800
+ TemplateFilteringService.getMatchingTemplates([[target.backendName, definition]], filter).length !== 1)
801
+ continue;
802
+ const authority = manager.getBindingAuthority(bindingId);
803
+ if (!authority ||
804
+ !context.sessionId ||
805
+ !validateProjectPreparationAuthority(authority, { bindingId, context, ownerSessionId: context.sessionId }))
806
+ continue;
807
+ let checkoutPath;
808
+ try {
809
+ checkoutPath = requireProjectTarget(context, 'single')[0].path;
810
+ }
811
+ catch {
812
+ continue;
813
+ }
814
+ // Only live verified binding contexts may authorize these canonicalization reads.
815
+ try {
816
+ if ((await fs.promises.realpath(checkoutPath)) !== target.checkoutRoot)
817
+ continue;
818
+ }
819
+ catch {
820
+ continue;
821
+ }
822
+ const connection = resolver.resolve(target.backendName, bindingId);
823
+ if (!connection)
824
+ continue;
825
+ if (options.onlyEmptyInventory) {
826
+ const tools = readConfiguredToolSnapshot(connection);
827
+ if (!tools || tools.length)
828
+ continue;
829
+ }
830
+ if (options.missingTool) {
831
+ const tools = readConfiguredToolSnapshot(connection);
832
+ // An absent snapshot will be enumerated by the actual invocation catalog. Preserve already-declared header fences.
833
+ if (!tools || tools.some((tool) => tool.name === options.missingTool))
834
+ continue;
835
+ }
836
+ connections.add(connection);
837
+ }
838
+ for (const connection of connections)
839
+ await invalidatePreparedToolProvider(connection);
840
+ if (connections.size)
841
+ await serverManager.getLazyLoadingOrchestrator()?.refreshCapabilities();
842
+ }
843
+ export function getBackendPreparationCoordinator(serverManager) {
844
+ let coordinator = runtimeCoordinators.get(serverManager);
845
+ if (coordinator)
846
+ return coordinator;
847
+ coordinator = new BackendPreparationCoordinator({
848
+ options: ConfigManager.getInstance().getAppConfig().preparation,
849
+ storagePath: AgentConfigManager.getInstance().get('runtimeScopeStoragePath'),
850
+ onReady: (target) => refreshPreparedBackendCapabilities(serverManager, target),
851
+ });
852
+ runtimeCoordinators.set(serverManager, coordinator);
853
+ serverManager.registerOwnedCleanup(async () => {
854
+ await coordinator.shutdown();
855
+ });
856
+ return coordinator;
857
+ }
858
+ /** Read-only lookup: lifecycle status must never initialize preparation. */
859
+ export function peekBackendPreparationCoordinator(serverManager) {
860
+ return runtimeCoordinators.get(serverManager);
861
+ }
862
+ /** A restarted runtime cannot infer that an advisory active job's external writer has exited. */
863
+ export function persistedProjectPreparationBlockers(checkout) {
864
+ const storage = AgentConfigManager.getInstance().get?.('runtimeScopeStoragePath');
865
+ if (!storage)
866
+ return [];
867
+ const file = path.join(storage, 'backend-preparation.json');
868
+ if (!fs.existsSync(file))
869
+ return [];
870
+ const fd = openCredentialReadSync(file);
871
+ try {
872
+ const stat = fs.fstatSync(fd);
873
+ if (!stat.isFile() || stat.size > 128 * 1024 * 1024)
874
+ throw new Error('Invalid preparation recovery storage');
875
+ const records = z.array(savedSchema).parse(JSON.parse(fs.readFileSync(fd, 'utf8')));
876
+ const canonical = canonicalLifecyclePath(checkout);
877
+ return records
878
+ .filter((record) => record.target.checkoutRoot === canonical && ['queued', 'running', 'cancelling'].includes(record.state))
879
+ .map((record) => ({ kind: 'preparation-recovery', id: record.previousJobId }));
880
+ }
881
+ finally {
882
+ fs.closeSync(fd);
883
+ }
884
+ }
885
+ //# sourceMappingURL=backendPreparationCoordinator.js.map