@evref-bl/plexus 0.15.2 → 0.16.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 (251) hide show
  1. package/README.md +8 -12
  2. package/dist/cli.js +8 -183
  3. package/dist/cli.js.map +1 -1
  4. package/dist/commandLine.d.ts +13 -0
  5. package/dist/commandLine.d.ts.map +1 -0
  6. package/dist/commandLine.js +247 -0
  7. package/dist/commandLine.js.map +1 -0
  8. package/dist/config/pharoMcpVersion.d.ts +6 -7
  9. package/dist/config/pharoMcpVersion.d.ts.map +1 -1
  10. package/dist/config/pharoMcpVersion.js +6 -7
  11. package/dist/config/pharoMcpVersion.js.map +1 -1
  12. package/dist/errors.d.ts +11 -0
  13. package/dist/errors.d.ts.map +1 -0
  14. package/dist/errors.js +17 -0
  15. package/dist/errors.js.map +1 -0
  16. package/dist/forward/endpointHandoffFormat.d.ts +23 -0
  17. package/dist/forward/endpointHandoffFormat.d.ts.map +1 -0
  18. package/dist/forward/endpointHandoffFormat.js.map +1 -0
  19. package/dist/forward/index.d.ts +20 -0
  20. package/dist/forward/index.d.ts.map +1 -0
  21. package/dist/forward/index.js +77 -0
  22. package/dist/forward/index.js.map +1 -0
  23. package/dist/forward/jsonRpc.d.ts +20 -0
  24. package/dist/forward/jsonRpc.d.ts.map +1 -0
  25. package/dist/forward/jsonRpc.js +141 -0
  26. package/dist/forward/jsonRpc.js.map +1 -0
  27. package/dist/home.d.ts +15 -0
  28. package/dist/home.d.ts.map +1 -0
  29. package/dist/home.js +30 -0
  30. package/dist/home.js.map +1 -0
  31. package/dist/images/bases.d.ts +40 -0
  32. package/dist/images/bases.d.ts.map +1 -0
  33. package/dist/images/bases.js +190 -0
  34. package/dist/images/bases.js.map +1 -0
  35. package/dist/images/claims.d.ts +34 -0
  36. package/dist/images/claims.d.ts.map +1 -0
  37. package/dist/images/claims.js +119 -0
  38. package/dist/images/claims.js.map +1 -0
  39. package/dist/images/context.d.ts +22 -0
  40. package/dist/images/context.d.ts.map +1 -0
  41. package/dist/images/context.js +26 -0
  42. package/dist/images/context.js.map +1 -0
  43. package/dist/images/create.d.ts +19 -0
  44. package/dist/images/create.d.ts.map +1 -0
  45. package/dist/images/create.js +121 -0
  46. package/dist/images/create.js.map +1 -0
  47. package/dist/images/delete.d.ts +10 -0
  48. package/dist/images/delete.d.ts.map +1 -0
  49. package/dist/images/delete.js +31 -0
  50. package/dist/images/delete.js.map +1 -0
  51. package/dist/images/endpoint.d.ts +17 -0
  52. package/dist/images/endpoint.d.ts.map +1 -0
  53. package/dist/images/endpoint.js +58 -0
  54. package/dist/images/endpoint.js.map +1 -0
  55. package/dist/images/index.d.ts +28 -0
  56. package/dist/images/index.d.ts.map +1 -0
  57. package/dist/images/index.js +51 -0
  58. package/dist/images/index.js.map +1 -0
  59. package/dist/images/leftovers.d.ts +9 -0
  60. package/dist/images/leftovers.d.ts.map +1 -0
  61. package/dist/images/leftovers.js +38 -0
  62. package/dist/images/leftovers.js.map +1 -0
  63. package/dist/images/list.d.ts +12 -0
  64. package/dist/images/list.d.ts.map +1 -0
  65. package/dist/images/list.js +74 -0
  66. package/dist/images/list.js.map +1 -0
  67. package/dist/images/names.d.ts +15 -0
  68. package/dist/images/names.d.ts.map +1 -0
  69. package/dist/images/names.js +53 -0
  70. package/dist/images/names.js.map +1 -0
  71. package/dist/images/prepare.d.ts +18 -0
  72. package/dist/images/prepare.d.ts.map +1 -0
  73. package/dist/images/prepare.js +58 -0
  74. package/dist/images/prepare.js.map +1 -0
  75. package/dist/images/processes.d.ts +21 -0
  76. package/dist/images/processes.d.ts.map +1 -0
  77. package/dist/images/processes.js +83 -0
  78. package/dist/images/processes.js.map +1 -0
  79. package/dist/images/scripts.d.ts +39 -0
  80. package/dist/images/scripts.d.ts.map +1 -0
  81. package/dist/images/scripts.js +127 -0
  82. package/dist/images/scripts.js.map +1 -0
  83. package/dist/images/start.d.ts +23 -0
  84. package/dist/images/start.d.ts.map +1 -0
  85. package/dist/images/start.js +173 -0
  86. package/dist/images/start.js.map +1 -0
  87. package/dist/images/stop.d.ts +11 -0
  88. package/dist/images/stop.d.ts.map +1 -0
  89. package/dist/images/stop.js +42 -0
  90. package/dist/images/stop.js.map +1 -0
  91. package/dist/images/store.d.ts +62 -0
  92. package/dist/images/store.d.ts.map +1 -0
  93. package/dist/images/store.js +180 -0
  94. package/dist/images/store.js.map +1 -0
  95. package/dist/images/templates.d.ts +14 -0
  96. package/dist/images/templates.d.ts.map +1 -0
  97. package/dist/images/templates.js +84 -0
  98. package/dist/images/templates.js.map +1 -0
  99. package/dist/index.d.ts +12 -22
  100. package/dist/index.d.ts.map +1 -1
  101. package/dist/index.js +8 -22
  102. package/dist/index.js.map +1 -1
  103. package/dist/launcher/pharoLauncherMcpClient.d.ts +22 -59
  104. package/dist/launcher/pharoLauncherMcpClient.d.ts.map +1 -1
  105. package/dist/launcher/pharoLauncherMcpClient.js +121 -98
  106. package/dist/launcher/pharoLauncherMcpClient.js.map +1 -1
  107. package/dist/launcher/pharoLauncherProfile.d.ts +5 -32
  108. package/dist/launcher/pharoLauncherProfile.d.ts.map +1 -1
  109. package/dist/launcher/pharoLauncherProfile.js +17 -115
  110. package/dist/launcher/pharoLauncherProfile.js.map +1 -1
  111. package/dist/mcp/server.d.ts +18 -0
  112. package/dist/mcp/server.d.ts.map +1 -0
  113. package/dist/mcp/server.js +206 -0
  114. package/dist/mcp/server.js.map +1 -0
  115. package/dist/types.d.ts +68 -0
  116. package/dist/types.d.ts.map +1 -0
  117. package/dist/types.js +2 -0
  118. package/dist/types.js.map +1 -0
  119. package/dist/version.d.ts +2 -0
  120. package/dist/version.d.ts.map +1 -0
  121. package/dist/version.js +5 -0
  122. package/dist/version.js.map +1 -0
  123. package/package.json +3 -12
  124. package/dist/config/config.d.ts +0 -15
  125. package/dist/config/config.d.ts.map +0 -1
  126. package/dist/config/config.js +0 -74
  127. package/dist/config/config.js.map +0 -1
  128. package/dist/config/plexusHome.d.ts +0 -17
  129. package/dist/config/plexusHome.d.ts.map +0 -1
  130. package/dist/config/plexusHome.js +0 -30
  131. package/dist/config/plexusHome.js.map +0 -1
  132. package/dist/config/projectConfig.d.ts +0 -141
  133. package/dist/config/projectConfig.d.ts.map +0 -1
  134. package/dist/config/projectConfig.js +0 -722
  135. package/dist/config/projectConfig.js.map +0 -1
  136. package/dist/config/projectConfigAuthoring.d.ts +0 -53
  137. package/dist/config/projectConfigAuthoring.d.ts.map +0 -1
  138. package/dist/config/projectConfigAuthoring.js +0 -159
  139. package/dist/config/projectConfigAuthoring.js.map +0 -1
  140. package/dist/gateway/projectImageMcpEndpoint.d.ts +0 -23
  141. package/dist/gateway/projectImageMcpEndpoint.d.ts.map +0 -1
  142. package/dist/gateway/projectImageMcpEndpoint.js +0 -40
  143. package/dist/gateway/projectImageMcpEndpoint.js.map +0 -1
  144. package/dist/gateway/server/index.d.ts +0 -8
  145. package/dist/gateway/server/index.d.ts.map +0 -1
  146. package/dist/gateway/server/index.js +0 -34
  147. package/dist/gateway/server/index.js.map +0 -1
  148. package/dist/gateway/server/mcp/server.d.ts +0 -66
  149. package/dist/gateway/server/mcp/server.d.ts.map +0 -1
  150. package/dist/gateway/server/mcp/server.js +0 -458
  151. package/dist/gateway/server/mcp/server.js.map +0 -1
  152. package/dist/gateway/server/routing/endpointHandoffFormat.d.ts +0 -26
  153. package/dist/gateway/server/routing/endpointHandoffFormat.d.ts.map +0 -1
  154. package/dist/gateway/server/routing/endpointHandoffFormat.js.map +0 -1
  155. package/dist/gateway/server/routing/gateway.d.ts +0 -167
  156. package/dist/gateway/server/routing/gateway.d.ts.map +0 -1
  157. package/dist/gateway/server/routing/gateway.js +0 -863
  158. package/dist/gateway/server/routing/gateway.js.map +0 -1
  159. package/dist/gateway/server/routing/imageMcpRouter.d.ts +0 -59
  160. package/dist/gateway/server/routing/imageMcpRouter.d.ts.map +0 -1
  161. package/dist/gateway/server/routing/imageMcpRouter.js +0 -253
  162. package/dist/gateway/server/routing/imageMcpRouter.js.map +0 -1
  163. package/dist/gateway/server/routing/pharoFacade.d.ts +0 -12
  164. package/dist/gateway/server/routing/pharoFacade.d.ts.map +0 -1
  165. package/dist/gateway/server/routing/pharoFacade.js +0 -67
  166. package/dist/gateway/server/routing/pharoFacade.js.map +0 -1
  167. package/dist/gateway/server/routing/routeDiscovery.d.ts +0 -26
  168. package/dist/gateway/server/routing/routeDiscovery.d.ts.map +0 -1
  169. package/dist/gateway/server/routing/routeDiscovery.js +0 -46
  170. package/dist/gateway/server/routing/routeDiscovery.js.map +0 -1
  171. package/dist/gateway/server/routing/routingTable.d.ts +0 -120
  172. package/dist/gateway/server/routing/routingTable.d.ts.map +0 -1
  173. package/dist/gateway/server/routing/routingTable.js +0 -215
  174. package/dist/gateway/server/routing/routingTable.js.map +0 -1
  175. package/dist/gateway/server/support/processLiveness.d.ts +0 -10
  176. package/dist/gateway/server/support/processLiveness.d.ts.map +0 -1
  177. package/dist/gateway/server/support/processLiveness.js +0 -25
  178. package/dist/gateway/server/support/processLiveness.js.map +0 -1
  179. package/dist/gateway/server/support/sourceBuildPreflight.d.ts +0 -15
  180. package/dist/gateway/server/support/sourceBuildPreflight.d.ts.map +0 -1
  181. package/dist/gateway/server/support/sourceBuildPreflight.js +0 -88
  182. package/dist/gateway/server/support/sourceBuildPreflight.js.map +0 -1
  183. package/dist/gateway/server/support/toolResultFormatting.d.ts +0 -8
  184. package/dist/gateway/server/support/toolResultFormatting.d.ts.map +0 -1
  185. package/dist/gateway/server/support/toolResultFormatting.js +0 -74
  186. package/dist/gateway/server/support/toolResultFormatting.js.map +0 -1
  187. package/dist/images/homeImageCache.d.ts +0 -302
  188. package/dist/images/homeImageCache.d.ts.map +0 -1
  189. package/dist/images/homeImageCache.js +0 -1031
  190. package/dist/images/homeImageCache.js.map +0 -1
  191. package/dist/images/imageRescue.d.ts +0 -151
  192. package/dist/images/imageRescue.d.ts.map +0 -1
  193. package/dist/images/imageRescue.js +0 -748
  194. package/dist/images/imageRescue.js.map +0 -1
  195. package/dist/images/imageRuntime.d.ts +0 -60
  196. package/dist/images/imageRuntime.d.ts.map +0 -1
  197. package/dist/images/imageRuntime.js +0 -90
  198. package/dist/images/imageRuntime.js.map +0 -1
  199. package/dist/images/preparedImageCache.d.ts +0 -86
  200. package/dist/images/preparedImageCache.d.ts.map +0 -1
  201. package/dist/images/preparedImageCache.js +0 -229
  202. package/dist/images/preparedImageCache.js.map +0 -1
  203. package/dist/images/scopedTemplateCatalog.d.ts +0 -33
  204. package/dist/images/scopedTemplateCatalog.d.ts.map +0 -1
  205. package/dist/images/scopedTemplateCatalog.js +0 -363
  206. package/dist/images/scopedTemplateCatalog.js.map +0 -1
  207. package/dist/internal.d.ts +0 -20
  208. package/dist/internal.d.ts.map +0 -1
  209. package/dist/internal.js +0 -20
  210. package/dist/internal.js.map +0 -1
  211. package/dist/launcher/scopedPharoLauncherServer.d.ts +0 -349
  212. package/dist/launcher/scopedPharoLauncherServer.d.ts.map +0 -1
  213. package/dist/launcher/scopedPharoLauncherServer.js +0 -1307
  214. package/dist/launcher/scopedPharoLauncherServer.js.map +0 -1
  215. package/dist/lifecycle/startProjectImage.d.ts +0 -94
  216. package/dist/lifecycle/startProjectImage.d.ts.map +0 -1
  217. package/dist/lifecycle/startProjectImage.js +0 -1054
  218. package/dist/lifecycle/startProjectImage.js.map +0 -1
  219. package/dist/lifecycle/stopProjectImage.d.ts +0 -31
  220. package/dist/lifecycle/stopProjectImage.d.ts.map +0 -1
  221. package/dist/lifecycle/stopProjectImage.js +0 -201
  222. package/dist/lifecycle/stopProjectImage.js.map +0 -1
  223. package/dist/mcp/agentServer.d.ts +0 -15
  224. package/dist/mcp/agentServer.d.ts.map +0 -1
  225. package/dist/mcp/agentServer.js +0 -67
  226. package/dist/mcp/agentServer.js.map +0 -1
  227. package/dist/mcp/imageOperations.d.ts +0 -54
  228. package/dist/mcp/imageOperations.d.ts.map +0 -1
  229. package/dist/mcp/imageOperations.js +0 -223
  230. package/dist/mcp/imageOperations.js.map +0 -1
  231. package/dist/mcp/pharoMcpHealth.d.ts +0 -26
  232. package/dist/mcp/pharoMcpHealth.d.ts.map +0 -1
  233. package/dist/mcp/pharoMcpHealth.js +0 -97
  234. package/dist/mcp/pharoMcpHealth.js.map +0 -1
  235. package/dist/support/pathStyle.d.ts +0 -11
  236. package/dist/support/pathStyle.d.ts.map +0 -1
  237. package/dist/support/pathStyle.js +0 -61
  238. package/dist/support/pathStyle.js.map +0 -1
  239. package/dist/support/toolResultFormatting.d.ts +0 -8
  240. package/dist/support/toolResultFormatting.d.ts.map +0 -1
  241. package/dist/support/toolResultFormatting.js +0 -74
  242. package/dist/support/toolResultFormatting.js.map +0 -1
  243. package/dist/workspace/projectStartupScript.d.ts +0 -73
  244. package/dist/workspace/projectStartupScript.d.ts.map +0 -1
  245. package/dist/workspace/projectStartupScript.js +0 -607
  246. package/dist/workspace/projectStartupScript.js.map +0 -1
  247. package/dist/workspace/projectState.d.ts +0 -216
  248. package/dist/workspace/projectState.d.ts.map +0 -1
  249. package/dist/workspace/projectState.js +0 -172
  250. package/dist/workspace/projectState.js.map +0 -1
  251. /package/dist/{gateway/server/routing → forward}/endpointHandoffFormat.js +0 -0
@@ -1,748 +0,0 @@
1
- import fs from "node:fs";
2
- import path from "node:path";
3
- import { loadProjectConfig, projectConfigId, resolveProjectRuntimePolicy, } from "../config/projectConfig.js";
4
- import { openPharoLauncherClient, } from "../launcher/pharoLauncherMcpClient.js";
5
- import { pharoLauncherMcpProfileEnvironment } from "../launcher/pharoLauncherProfile.js";
6
- import { HttpPharoMcpHealthClient, } from "../mcp/pharoMcpHealth.js";
7
- import { applyChangeHistoryEntries, changeHistorySelectionArguments, highestChangeHistoryEntryIndex, listChangeHistoryFiles, listRegisteredRepositories, repositoryArguments, repositoryRegistrationToolName, runImageTool, } from "../mcp/imageOperations.js";
8
- import { defaultWorkspaceId, loadProjectState, projectStatePath, runtimeStatusForImages, sanitizeRuntimeId, saveProjectState, } from "../workspace/projectState.js";
9
- import { imageMcpEndpointHandoffPath, readImageMcpEndpointHandoff, removeImageMcpEndpointHandoff, } from "../gateway/projectImageMcpEndpoint.js";
10
- import { writeImageStartupScript } from "../workspace/projectStartupScript.js";
11
- const defaultPoll = {
12
- intervalMs: 500,
13
- processTimeoutMs: 30_000,
14
- healthTimeoutMs: 5 * 60_000,
15
- };
16
- export class ImageRescueError extends Error {
17
- result;
18
- constructor(message, result) {
19
- super(message);
20
- this.result = result;
21
- this.name = "ImageRescueError";
22
- }
23
- }
24
- function defaultSleep(durationMs) {
25
- return new Promise((resolve) => setTimeout(resolve, durationMs));
26
- }
27
- function errorMessage(error) {
28
- return error instanceof Error ? error.message : String(error);
29
- }
30
- function isObject(value) {
31
- return Boolean(value) && typeof value === "object" && !Array.isArray(value);
32
- }
33
- function launcherResultData(result) {
34
- if (isObject(result) && "data" in result) {
35
- const commandResult = result;
36
- return commandResult.ok === false ? undefined : commandResult.data;
37
- }
38
- return result;
39
- }
40
- function assertLauncherOk(result, toolName) {
41
- if (isObject(result) && result.ok === false) {
42
- throw new Error(`${toolName} returned ok: false`);
43
- }
44
- }
45
- function nowStamp(now) {
46
- return now().toISOString().replaceAll(/[:.]/g, "-");
47
- }
48
- function defaultTargetImageId(sourceImageId) {
49
- return sanitizeRuntimeId(`${sourceImageId}-rescue`);
50
- }
51
- function defaultTargetImageName(sourceImageName, now) {
52
- return `${sourceImageName}-rescue-${nowStamp(now).slice(0, 19)}`;
53
- }
54
- function processMatchesImage(process, imageName) {
55
- return (process.imageName === imageName ||
56
- path.basename(process.imagePath ?? "", ".image") === imageName ||
57
- process.commandLine.includes(`${imageName}.image`) ||
58
- process.commandLine.includes(imageName));
59
- }
60
- async function pollUntil(timeoutMs, intervalMs, sleep, producer) {
61
- const startedAt = Date.now();
62
- while (Date.now() - startedAt <= timeoutMs) {
63
- const result = await producer();
64
- if (result !== undefined) {
65
- return result;
66
- }
67
- await sleep(intervalMs);
68
- }
69
- return undefined;
70
- }
71
- async function pollProcessForImage(client, imageName, timeoutMs, intervalMs, sleep) {
72
- return pollUntil(timeoutMs, intervalMs, sleep, async () => {
73
- const result = await client.callTool("pharo_launcher_process_list");
74
- const processes = launcherResultData(result) ?? [];
75
- return processes.find((process) => processMatchesImage(process, imageName));
76
- });
77
- }
78
- async function launchImage(client, healthClient, imageState, startupScriptPath, endpointHandoffPath, poll, sleep) {
79
- const launchResult = await client.callTool("pharo_launcher_image_start", {
80
- imageName: imageState.imageName,
81
- detached: true,
82
- displayMode: "headless",
83
- script: startupScriptPath,
84
- });
85
- assertLauncherOk(launchResult, "pharo_launcher_image_start");
86
- const process = await pollProcessForImage(client, imageState.imageName, poll.processTimeoutMs, poll.intervalMs, sleep);
87
- if (!process) {
88
- throw new Error(`Timed out waiting for PharoLauncher process for image ${imageState.imageName}`);
89
- }
90
- const endpoint = await pollUntil(poll.healthTimeoutMs, poll.intervalMs, sleep, async () => {
91
- const handoff = readImageMcpEndpointHandoff(endpointHandoffPath);
92
- if (handoff.status !== "valid") {
93
- return undefined;
94
- }
95
- const healthy = healthClient.checkEndpoint
96
- ? await healthClient.checkEndpoint(handoff.endpoint)
97
- : await healthClient.check(handoff.endpoint.port);
98
- return healthy ? handoff.endpoint : undefined;
99
- });
100
- if (!endpoint) {
101
- throw new Error(`Timed out waiting for Pharo MCP to write its endpoint to ${endpointHandoffPath}`);
102
- }
103
- imageState.mcpServers = [{ id: imageState.id, endpoint }];
104
- return process.pid;
105
- }
106
- function resolveWorkspaceId(projectRoot, workspaceId) {
107
- return workspaceId ? sanitizeRuntimeId(workspaceId) : defaultWorkspaceId(projectRoot);
108
- }
109
- function findImageState(state, imageId) {
110
- const image = state.images.find((candidate) => candidate.id === imageId);
111
- if (!image) {
112
- throw new ImageRescueError(`Project state does not contain image id: ${imageId}`);
113
- }
114
- return image;
115
- }
116
- function findImageConfig(configImages, imageId) {
117
- const image = configImages.find((candidate) => candidate.id === imageId);
118
- if (!image) {
119
- throw new ImageRescueError(`Project config does not contain image id: ${imageId}`);
120
- }
121
- return image;
122
- }
123
- function launcherImagesDirectory(configReport) {
124
- return (configReport.profile?.imagesDir?.path ??
125
- (configReport.launcherDir?.path
126
- ? path.join(configReport.launcherDir.path, "images")
127
- : undefined));
128
- }
129
- function resolveLauncherImagePath(imageName, rawImagePath, imagesDirectory) {
130
- if (rawImagePath) {
131
- return path.isAbsolute(rawImagePath)
132
- ? rawImagePath
133
- : imagesDirectory
134
- ? path.resolve(imagesDirectory, rawImagePath)
135
- : path.resolve(rawImagePath);
136
- }
137
- return imagesDirectory
138
- ? path.join(imagesDirectory, imageName, `${imageName}.image`)
139
- : undefined;
140
- }
141
- function resolveImagePaths(imageName, launcherImage, configReport) {
142
- const rawImagePath = launcherImage?.imagePath;
143
- const imagesDirectory = launcherImagesDirectory(configReport);
144
- const imagePath = resolveLauncherImagePath(imageName, rawImagePath, imagesDirectory);
145
- const imageDirectoryPath = imagePath ? path.dirname(imagePath) : undefined;
146
- const changesPath = imagePath
147
- ? imagePath.replace(/\.image$/i, ".changes")
148
- : undefined;
149
- const localDirectoryPath = imageDirectoryPath
150
- ? path.join(imageDirectoryPath, "pharo-local")
151
- : undefined;
152
- const ombuDirectoryPath = localDirectoryPath
153
- ? path.join(localDirectoryPath, "ombu-sessions")
154
- : undefined;
155
- return {
156
- ...(imagePath ? { imagePath } : {}),
157
- ...(imageDirectoryPath ? { imageDirectoryPath } : {}),
158
- ...(changesPath ? { changesPath } : {}),
159
- ...(localDirectoryPath ? { localDirectoryPath } : {}),
160
- ...(ombuDirectoryPath ? { ombuDirectoryPath } : {}),
161
- };
162
- }
163
- async function launcherImageInfo(client, imageName) {
164
- const result = await client.callTool("pharo_launcher_image_info", {
165
- imageName,
166
- format: "ston",
167
- });
168
- return launcherResultData(result);
169
- }
170
- async function launcherConfigReport(client) {
171
- const result = await client.callTool("pharo_launcher_config");
172
- return launcherResultData(result) ?? {};
173
- }
174
- async function snapshotRepositories(image, imageMcpClient, capturedAt) {
175
- if (!imageMcpClient || image.status !== "running") {
176
- return undefined;
177
- }
178
- try {
179
- const repositories = await listRegisteredRepositories(imageMcpClient, image);
180
- return {
181
- capturedAt,
182
- status: "captured",
183
- repositories,
184
- };
185
- }
186
- catch (error) {
187
- return {
188
- capturedAt,
189
- status: "unavailable",
190
- repositories: [],
191
- error: errorMessage(error),
192
- };
193
- }
194
- }
195
- function listOmbuFiles(directoryPath) {
196
- if (!directoryPath || !fs.existsSync(directoryPath)) {
197
- return [];
198
- }
199
- return fs
200
- .readdirSync(directoryPath, { withFileTypes: true })
201
- .filter((entry) => entry.isFile() && entry.name.endsWith(".ombu"))
202
- .map((entry) => {
203
- const filePath = path.join(directoryPath, entry.name);
204
- const stat = fs.statSync(filePath);
205
- return {
206
- path: filePath,
207
- mtimeMs: stat.mtimeMs,
208
- size: stat.size,
209
- };
210
- })
211
- .sort((a, b) => (b.mtimeMs ?? 0) - (a.mtimeMs ?? 0));
212
- }
213
- function excludedIndexes(exclude) {
214
- if (exclude?.latestCount !== undefined) {
215
- throw new ImageRescueError("exclude.latestCount cannot be inverted safely yet; use indexes or ranges");
216
- }
217
- const indexes = new Set(exclude?.indexes ?? []);
218
- if (exclude?.startIndex !== undefined && exclude.endIndex !== undefined) {
219
- for (let index = exclude.startIndex; index <= exclude.endIndex; index += 1) {
220
- indexes.add(index);
221
- }
222
- }
223
- return indexes;
224
- }
225
- async function resolveSelectionWithExclusions(imageMcpClient, targetImage, historyFilePath, selection, exclude, codeChangesOnly) {
226
- if (!exclude) {
227
- return selection;
228
- }
229
- if (exclude.entryReferences && exclude.entryReferences.length > 0) {
230
- throw new ImageRescueError("exclude.entryReferences cannot be inverted safely yet; use indexes or ranges");
231
- }
232
- const excludes = excludedIndexes(exclude);
233
- const selected = await selectedRange(imageMcpClient, targetImage, historyFilePath, selection, codeChangesOnly);
234
- return {
235
- indexes: selected.filter((index) => !excludes.has(index)),
236
- };
237
- }
238
- // Every index the selection covers. One that names them outright is answered
239
- // here; one that reaches to the end of the file needs the image to say where
240
- // that is, because an exclusion can only be subtracted from a known range.
241
- async function selectedRange(imageMcpClient, targetImage, historyFilePath, selection, codeChangesOnly) {
242
- if (selection?.entryReferences && selection.entryReferences.length > 0) {
243
- throw new ImageRescueError("selection.entryReferences cannot be combined with exclude yet; use indexes or ranges");
244
- }
245
- if (selection?.latestCount !== undefined) {
246
- throw new ImageRescueError("selection.latestCount cannot be combined with exclude yet; use indexes or ranges");
247
- }
248
- if (selection?.indexes && selection.indexes.length > 0) {
249
- const startIndex = selection.startIndex ?? Number.NEGATIVE_INFINITY;
250
- const endIndex = selection.endIndex ?? Number.POSITIVE_INFINITY;
251
- return [...new Set(selection.indexes)]
252
- .filter((index) => index >= startIndex && index <= endIndex)
253
- .sort((left, right) => left - right);
254
- }
255
- const startIndex = selection?.startIndex ?? 1;
256
- const endIndex = selection?.endIndex ??
257
- (await highestChangeHistoryEntryIndex(imageMcpClient, targetImage, {
258
- historyFilePath,
259
- codeChangesOnly,
260
- }));
261
- if (endIndex === undefined) {
262
- throw new ImageRescueError("Could not read how far the entries reach while applying exclusions");
263
- }
264
- const range = [];
265
- for (let index = startIndex; index <= endIndex; index += 1) {
266
- range.push(index);
267
- }
268
- return range;
269
- }
270
- function defaultRepositoryActions(snapshot) {
271
- if (!snapshot || snapshot.status !== "captured") {
272
- return [];
273
- }
274
- // The image lists how many packages a repository manages, not which, so a
275
- // rescued registration carries the checkout and nothing more. Opening the
276
- // project puts the workspace's own package membership back. One whose
277
- // checkout is gone has nothing to register.
278
- return snapshot.repositories.flatMap((repository) => repository.location
279
- ? [
280
- {
281
- label: `Register repository ${repository.name}`,
282
- toolName: repositoryRegistrationToolName,
283
- arguments: repositoryArguments({
284
- ...repository,
285
- location: repository.location,
286
- }),
287
- },
288
- ]
289
- : []);
290
- }
291
- async function runRepositoryActions(imageMcpClient, targetImage, actions, confirm) {
292
- const results = [];
293
- for (const action of actions) {
294
- const toolName = action.toolName ?? repositoryRegistrationToolName;
295
- const label = action.label ?? toolName;
296
- if (!confirm) {
297
- results.push({
298
- label,
299
- toolName,
300
- arguments: action.arguments,
301
- status: "planned",
302
- });
303
- continue;
304
- }
305
- if (!imageMcpClient || !targetImage) {
306
- results.push({
307
- label,
308
- toolName,
309
- arguments: action.arguments,
310
- status: "skipped",
311
- error: "No target image MCP client is available",
312
- });
313
- continue;
314
- }
315
- try {
316
- const result = await runImageTool(imageMcpClient, targetImage, toolName, action.arguments);
317
- results.push({
318
- label,
319
- toolName,
320
- arguments: action.arguments,
321
- status: "applied",
322
- result,
323
- });
324
- }
325
- catch (error) {
326
- results.push({
327
- label,
328
- toolName,
329
- arguments: action.arguments,
330
- status: "failed",
331
- error: errorMessage(error),
332
- });
333
- }
334
- }
335
- return results;
336
- }
337
- function selectedHistoryFile(historyFilePath, historyFiles) {
338
- return historyFilePath ?? historyFiles[0]?.path;
339
- }
340
- function pathIsInsideDirectory(filePath, directoryPath) {
341
- const relativePath = path.relative(path.resolve(directoryPath), path.resolve(filePath));
342
- return (relativePath === "" ||
343
- (relativePath.length > 0 &&
344
- !relativePath.startsWith("..") &&
345
- !path.isAbsolute(relativePath)));
346
- }
347
- function assertPathInsideDirectory(filePath, directoryPath, label) {
348
- if (!directoryPath || !pathIsInsideDirectory(filePath, directoryPath)) {
349
- throw new ImageRescueError(`${label} must be inside ${directoryPath ?? "the source image boundary"}`);
350
- }
351
- }
352
- // The image no longer counts the entries in a history file, so what it adds to
353
- // the files PLexus already found on disk is which one is the session in
354
- // progress.
355
- async function listHistoryFilesThroughImage(imageMcpClient, image, directoryPath) {
356
- if (!imageMcpClient || !image || image.status !== "running" || !directoryPath) {
357
- return undefined;
358
- }
359
- return listChangeHistoryFiles(imageMcpClient, image, { directoryPath });
360
- }
361
- async function applyHistoryEntries(imageMcpClient, targetImage, historyFilePath, selection, exclude, codeChangesOnly, confirm) {
362
- if (!historyFilePath) {
363
- return undefined;
364
- }
365
- if (selection?.entryReferences && selection.entryReferences.length > 0) {
366
- throw new ImageRescueError("selection.entryReferences is not supported: the image names entries by index, range or latest count");
367
- }
368
- let resolvedSelection = selection;
369
- if (imageMcpClient && targetImage) {
370
- resolvedSelection = await resolveSelectionWithExclusions(imageMcpClient, targetImage, historyFilePath, selection, exclude, codeChangesOnly);
371
- }
372
- const argumentsValue = {
373
- historyFilePath,
374
- codeChangesOnly,
375
- confirm,
376
- ...changeHistorySelectionArguments(resolvedSelection),
377
- };
378
- if (!confirm) {
379
- return {
380
- historyFilePath,
381
- arguments: argumentsValue,
382
- status: "planned",
383
- };
384
- }
385
- if (!imageMcpClient || !targetImage) {
386
- throw new ImageRescueError("A running target image is required to apply history entries");
387
- }
388
- try {
389
- const result = await applyChangeHistoryEntries(imageMcpClient, targetImage, {
390
- historyFilePath,
391
- selection: resolvedSelection,
392
- codeChangesOnly,
393
- confirm,
394
- });
395
- return {
396
- historyFilePath,
397
- arguments: argumentsValue,
398
- status: "applied",
399
- result,
400
- };
401
- }
402
- catch (error) {
403
- return {
404
- historyFilePath,
405
- arguments: argumentsValue,
406
- status: "failed",
407
- error: errorMessage(error),
408
- failureClass: "apply-time-breaker",
409
- };
410
- }
411
- }
412
- function updateImageMetadata(image, snapshot) {
413
- image.imagePath = snapshot.paths.imagePath;
414
- image.imageDirectoryPath = snapshot.paths.imageDirectoryPath;
415
- image.changesPath = snapshot.paths.changesPath;
416
- image.localDirectoryPath = snapshot.paths.localDirectoryPath;
417
- image.ombuDirectoryPath = snapshot.paths.ombuDirectoryPath;
418
- image.vmId = snapshot.launcherImage?.vmId;
419
- image.pharoVersion = snapshot.launcherImage?.pharoVersion;
420
- image.originTemplate = snapshot.launcherImage?.originTemplate;
421
- image.rescueSnapshot = snapshot;
422
- }
423
- function targetConfigFromSource(sourceConfig, targetImageId, targetImageName) {
424
- return {
425
- ...sourceConfig,
426
- id: targetImageId,
427
- imageName: targetImageName,
428
- };
429
- }
430
- function saveImageRescueState(statePath, state) {
431
- state.runtimeStatus = runtimeStatusForImages(state.images);
432
- saveProjectState(statePath, state);
433
- }
434
- async function createTargetImage(client, targetImageName, templateName, templateCategory) {
435
- const result = await client.callTool("pharo_launcher_image_create", {
436
- newImageName: targetImageName,
437
- templateName,
438
- ...(templateCategory ? { templateCategory } : {}),
439
- noLaunch: true,
440
- });
441
- assertLauncherOk(result, "pharo_launcher_image_create");
442
- }
443
- function assertWorkspaceImagePolicyAllowsTarget(config, state, targetImageId) {
444
- const maxCount = resolveProjectRuntimePolicy(config).workspaceImages?.maxCount;
445
- if (maxCount === undefined || state.images.length < maxCount) {
446
- return;
447
- }
448
- throw new ImageRescueError(`Workspace image policy allows at most ${maxCount} image${maxCount === 1 ? "" : "s"}; rescue target image ${targetImageId} is rejected`);
449
- }
450
- function targetRoute(targetImageId) {
451
- return {
452
- serverName: "pharo_gateway",
453
- targetKey: "workspaceId",
454
- imageArgument: "mcpServerId",
455
- imageId: targetImageId,
456
- };
457
- }
458
- function buildTargetPlan(input) {
459
- assertWorkspaceImagePolicyAllowsTarget(input.config, input.state, input.targetImageId);
460
- return {
461
- targetImageId: input.targetImageId,
462
- targetImageName: input.targetImageName,
463
- templateName: input.templateName,
464
- ...(input.templateCategory
465
- ? { templateCategory: input.templateCategory }
466
- : {}),
467
- cleanupPolicy: "workspace_cleanup_only",
468
- route: targetRoute(input.targetImageId),
469
- creationTool: {
470
- name: "pharo_launcher_image_create",
471
- arguments: {
472
- newImageName: input.targetImageName,
473
- templateName: input.templateName,
474
- ...(input.templateCategory
475
- ? { templateCategory: input.templateCategory }
476
- : {}),
477
- noLaunch: true,
478
- },
479
- },
480
- };
481
- }
482
- async function createImageRescueContext(options) {
483
- const projectRoot = path.resolve(options.projectRoot);
484
- const config = loadProjectConfig(projectRoot);
485
- const workspaceId = resolveWorkspaceId(projectRoot, options.workspaceId);
486
- const resolvedStateRoot = options.stateRoot;
487
- const statePath = projectStatePath({
488
- projectRoot,
489
- stateRoot: resolvedStateRoot,
490
- });
491
- const state = loadProjectState(statePath);
492
- if (!state) {
493
- throw new ImageRescueError(`No PLexus runtime state found at ${statePath}`);
494
- }
495
- const now = options.now ?? (() => new Date());
496
- const capturedAt = now().toISOString();
497
- const sourceImage = findImageState(state, options.sourceImageId);
498
- const sourceConfig = findImageConfig(config.images, options.sourceImageId);
499
- const launcherClient = options.pharoLauncherMcpClient ??
500
- (openPharoLauncherClient({
501
- profileEnvironment: pharoLauncherMcpProfileEnvironment({
502
- projectRoot,
503
- config,
504
- workspaceId,
505
- stateRoot: resolvedStateRoot,
506
- }),
507
- }));
508
- return {
509
- options,
510
- projectRoot,
511
- config,
512
- workspaceId,
513
- resolvedStateRoot,
514
- statePath,
515
- state,
516
- now,
517
- capturedAt,
518
- sourceImage,
519
- sourceConfig,
520
- launcherClient,
521
- ownsLauncherClient: !options.pharoLauncherMcpClient,
522
- warnings: [],
523
- };
524
- }
525
- async function captureImageRescueSource(context) {
526
- const { capturedAt, launcherClient, options, sourceImage } = context;
527
- const [configReport, launcherImage] = await Promise.all([
528
- launcherConfigReport(launcherClient),
529
- launcherImageInfo(launcherClient, sourceImage.imageName),
530
- ]);
531
- const paths = resolveImagePaths(sourceImage.imageName, launcherImage, configReport);
532
- const repositorySnapshot = (await snapshotRepositories(sourceImage, options.imageMcpClient, capturedAt)) ?? sourceImage.rescueSnapshot?.repositories;
533
- const sourceSnapshot = {
534
- capturedAt,
535
- ...(launcherImage ? { launcherImage } : {}),
536
- paths,
537
- ...(repositorySnapshot ? { repositories: repositorySnapshot } : {}),
538
- };
539
- const historyDirectoryPath = options.sourceHistoryDirectoryPath ?? paths.ombuDirectoryPath;
540
- if (options.sourceHistoryDirectoryPath) {
541
- assertPathInsideDirectory(options.sourceHistoryDirectoryPath, paths.localDirectoryPath ?? paths.imageDirectoryPath, "sourceHistoryDirectoryPath");
542
- }
543
- const historyFiles = listOmbuFiles(historyDirectoryPath);
544
- const selectedHistoryFilePath = selectedHistoryFile(options.historyFilePath, historyFiles);
545
- if (selectedHistoryFilePath) {
546
- assertPathInsideDirectory(selectedHistoryFilePath, historyDirectoryPath, "historyFilePath");
547
- }
548
- return {
549
- sourceSnapshot,
550
- repositorySnapshot,
551
- historyDirectoryPath,
552
- historyFiles,
553
- selectedHistoryFilePath,
554
- };
555
- }
556
- function planImageRescueTarget(context, launcherImage) {
557
- const { config, now, options, sourceImage, state } = context;
558
- const targetImageId = options.targetImageId ?? defaultTargetImageId(options.sourceImageId);
559
- const targetImage = state.images.find((image) => image.id === targetImageId);
560
- const shouldPlanReplacement = options.operation === "plan" || options.operation === "prepareTarget";
561
- const plannedTargetImageName = shouldPlanReplacement
562
- ? options.targetImageName ??
563
- defaultTargetImageName(sourceImage.imageName, now)
564
- : undefined;
565
- const plannedTemplateName = shouldPlanReplacement
566
- ? options.targetTemplateName ?? launcherImage?.originTemplate?.name
567
- : undefined;
568
- const replacementPlan = shouldPlanReplacement &&
569
- !targetImage &&
570
- plannedTargetImageName &&
571
- plannedTemplateName
572
- ? buildTargetPlan({
573
- state,
574
- config,
575
- targetImageId,
576
- targetImageName: plannedTargetImageName,
577
- templateName: plannedTemplateName,
578
- templateCategory: options.targetTemplateCategory,
579
- })
580
- : undefined;
581
- return { targetImageId, targetImage, replacementPlan };
582
- }
583
- async function collectImageRescueHistoryListing(context, source, target) {
584
- const { options, sourceImage, warnings } = context;
585
- if (options.operation !== "plan" || !options.includeEntryCounts) {
586
- return undefined;
587
- }
588
- const historyReader = target.targetImage?.status === "running" ? target.targetImage : sourceImage;
589
- try {
590
- return await listHistoryFilesThroughImage(options.imageMcpClient, historyReader, source.historyDirectoryPath);
591
- }
592
- catch (error) {
593
- warnings.push(`Could not list history files through Pharo: ${errorMessage(error)}`);
594
- return undefined;
595
- }
596
- }
597
- function warnWhenRepositorySnapshotUnavailable(context, source) {
598
- if ((context.options.operation === "snapshotSource" ||
599
- context.options.operation === "prepareTarget") &&
600
- source.repositorySnapshot?.status === "unavailable") {
601
- context.warnings.push(`Repository snapshot is unavailable: ${source.repositorySnapshot.error ?? "unknown error"}`);
602
- }
603
- }
604
- function saveSourceSnapshot(context, source) {
605
- updateImageMetadata(context.sourceImage, source.sourceSnapshot);
606
- context.state.updatedAt = context.capturedAt;
607
- saveImageRescueState(context.statePath, context.state);
608
- }
609
- function imageRescueResultBase(context, source, target, historyListing) {
610
- return {
611
- operation: context.options.operation,
612
- projectRoot: context.projectRoot,
613
- statePath: context.statePath,
614
- state: context.state,
615
- sourceImage: context.sourceImage,
616
- ...(target.targetImage ? { targetImage: target.targetImage } : {}),
617
- sourceSnapshot: source.sourceSnapshot,
618
- historyDirectoryPath: source.historyDirectoryPath,
619
- historyFiles: source.historyFiles,
620
- historyListing,
621
- selectedHistoryFilePath: source.selectedHistoryFilePath,
622
- ...(target.replacementPlan ? { targetPlan: target.replacementPlan } : {}),
623
- warnings: context.warnings,
624
- };
625
- }
626
- function snapshotSourceResult(context, source, target, historyListing) {
627
- saveSourceSnapshot(context, source);
628
- return {
629
- ok: true,
630
- ...imageRescueResultBase(context, source, target, historyListing),
631
- };
632
- }
633
- async function prepareRescueTarget(context, source, target, historyListing) {
634
- if (target.targetImage) {
635
- throw new ImageRescueError(`Target image id already exists: ${target.targetImageId}`);
636
- }
637
- if (!target.replacementPlan) {
638
- throw new ImageRescueError("targetTemplateName is required because the source image origin template is unknown");
639
- }
640
- const replacementPlan = target.replacementPlan;
641
- await createTargetImage(context.launcherClient, replacementPlan.targetImageName, replacementPlan.templateName, replacementPlan.templateCategory);
642
- const targetImage = {
643
- id: target.targetImageId,
644
- imageName: replacementPlan.targetImageName,
645
- status: "starting",
646
- creation: {
647
- role: "rescue",
648
- source: {
649
- kind: "template",
650
- ...(context.sourceConfig.create?.profileId
651
- ? { profileId: context.sourceConfig.create.profileId }
652
- : {}),
653
- templateName: replacementPlan.templateName,
654
- ...(replacementPlan.templateCategory
655
- ? { templateCategory: replacementPlan.templateCategory }
656
- : {}),
657
- },
658
- cleanupPolicy: replacementPlan.cleanupPolicy,
659
- route: replacementPlan.route,
660
- },
661
- };
662
- target.targetImage = targetImage;
663
- context.state.images.push(targetImage);
664
- saveSourceSnapshot(context, source);
665
- const targetConfig = targetConfigFromSource(context.sourceConfig, target.targetImageId, replacementPlan.targetImageName);
666
- const endpointHandoffPath = imageMcpEndpointHandoffPath({
667
- projectRoot: context.projectRoot,
668
- imageId: target.targetImageId,
669
- stateRoot: context.resolvedStateRoot,
670
- });
671
- removeImageMcpEndpointHandoff(endpointHandoffPath);
672
- const startupScript = writeImageStartupScript({
673
- projectRoot: context.projectRoot,
674
- projectId: projectConfigId(context.config),
675
- workspaceId: context.workspaceId,
676
- stateRoot: context.resolvedStateRoot,
677
- imageConfig: targetConfig,
678
- imageState: targetImage,
679
- endpointHandoffPath,
680
- });
681
- const poll = {
682
- ...defaultPoll,
683
- ...context.options.poll,
684
- };
685
- try {
686
- const pid = await launchImage(context.launcherClient, context.options.healthClient ?? new HttpPharoMcpHealthClient(), targetImage, startupScript.filePath, endpointHandoffPath, poll, context.options.sleep ?? defaultSleep);
687
- targetImage.pid = pid;
688
- targetImage.status = "running";
689
- context.state.updatedAt = context.now().toISOString();
690
- saveImageRescueState(context.statePath, context.state);
691
- }
692
- catch (error) {
693
- targetImage.status = "failed";
694
- context.state.updatedAt = context.now().toISOString();
695
- saveImageRescueState(context.statePath, context.state);
696
- throw error;
697
- }
698
- return {
699
- ok: true,
700
- ...imageRescueResultBase(context, source, target, historyListing),
701
- };
702
- }
703
- async function applyImageRescuePlan(context, source, target, historyListing) {
704
- if (!target.targetImage) {
705
- throw new ImageRescueError(`Target image id is not in runtime state: ${target.targetImageId}`);
706
- }
707
- const actionSource = context.options.repositoryActions ??
708
- ((context.options.loadRepositories ?? true)
709
- ? defaultRepositoryActions(source.repositorySnapshot)
710
- : []);
711
- const repositoryResults = await runRepositoryActions(context.options.imageMcpClient, target.targetImage, actionSource, context.options.confirm === true);
712
- const changeResult = await applyHistoryEntries(context.options.imageMcpClient, target.targetImage, source.selectedHistoryFilePath, context.options.selection, context.options.exclude, context.options.codeChangesOnly ?? true, context.options.confirm === true);
713
- return {
714
- ok: repositoryResults.every((repository) => repository.status !== "failed") &&
715
- changeResult?.status !== "failed",
716
- ...imageRescueResultBase(context, source, target, historyListing),
717
- repositoryResults,
718
- changeResult,
719
- };
720
- }
721
- export async function rescueImage(options) {
722
- const context = await createImageRescueContext(options);
723
- try {
724
- const source = await captureImageRescueSource(context);
725
- const target = planImageRescueTarget(context, source.sourceSnapshot.launcherImage);
726
- const historyListing = await collectImageRescueHistoryListing(context, source, target);
727
- warnWhenRepositorySnapshotUnavailable(context, source);
728
- if (options.operation === "snapshotSource") {
729
- return snapshotSourceResult(context, source, target, historyListing);
730
- }
731
- if (options.operation === "prepareTarget") {
732
- return prepareRescueTarget(context, source, target, historyListing);
733
- }
734
- if (options.operation === "applyPlan") {
735
- return applyImageRescuePlan(context, source, target, historyListing);
736
- }
737
- return {
738
- ok: true,
739
- ...imageRescueResultBase(context, source, target, historyListing),
740
- };
741
- }
742
- finally {
743
- if (context.ownsLauncherClient) {
744
- await context.launcherClient.close?.();
745
- }
746
- }
747
- }
748
- //# sourceMappingURL=imageRescue.js.map