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