@evref-bl/plexus 0.1.0-alpha.0 → 0.1.1

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 (167) hide show
  1. package/dist/cli.js +1 -3
  2. package/dist/cli.js.map +1 -1
  3. package/dist/config/projectConfig.d.ts +2 -7
  4. package/dist/config/projectConfig.d.ts.map +1 -1
  5. package/dist/config/projectConfig.js +5 -27
  6. package/dist/config/projectConfig.js.map +1 -1
  7. package/dist/gateway/projectGateway.js +9 -9
  8. package/dist/gateway/projectGateway.js.map +1 -1
  9. package/dist/images/homeImageCache.d.ts +1 -1
  10. package/dist/images/homeImageCache.d.ts.map +1 -1
  11. package/dist/images/homeImageCache.js +3 -3
  12. package/dist/images/homeImageCache.js.map +1 -1
  13. package/dist/images/preparedImageCache.d.ts +1 -1
  14. package/dist/images/preparedImageCache.d.ts.map +1 -1
  15. package/dist/images/preparedImageCache.js +3 -3
  16. package/dist/images/preparedImageCache.js.map +1 -1
  17. package/dist/index.d.ts +0 -1
  18. package/dist/index.d.ts.map +1 -1
  19. package/dist/index.js +0 -1
  20. package/dist/index.js.map +1 -1
  21. package/dist/launcher/scopedPharoLauncherServer.d.ts +2 -2
  22. package/dist/launcher/scopedPharoLauncherServer.d.ts.map +1 -1
  23. package/dist/launcher/scopedPharoLauncherServer.js +7 -22
  24. package/dist/launcher/scopedPharoLauncherServer.js.map +1 -1
  25. package/dist/lifecycle/projectCleanup.js +1 -1
  26. package/dist/lifecycle/projectCleanup.js.map +1 -1
  27. package/dist/lifecycle/projectClose.js +1 -1
  28. package/dist/lifecycle/projectClose.js.map +1 -1
  29. package/dist/lifecycle/projectLifecycle.d.ts +5 -12
  30. package/dist/lifecycle/projectLifecycle.d.ts.map +1 -1
  31. package/dist/lifecycle/projectLifecycle.js +10 -46
  32. package/dist/lifecycle/projectLifecycle.js.map +1 -1
  33. package/dist/lifecycle/projectOpen.d.ts.map +1 -1
  34. package/dist/lifecycle/projectOpen.js +14 -15
  35. package/dist/lifecycle/projectOpen.js.map +1 -1
  36. package/dist/support/runtimeIdentity.d.ts +0 -2
  37. package/dist/support/runtimeIdentity.d.ts.map +1 -1
  38. package/dist/support/runtimeIdentity.js +0 -2
  39. package/dist/support/runtimeIdentity.js.map +1 -1
  40. package/dist/workspace/projectState.d.ts +1 -2
  41. package/dist/workspace/projectState.d.ts.map +1 -1
  42. package/dist/workspace/projectState.js.map +1 -1
  43. package/dist/workspace/scopedProjectContext.d.ts +1 -1
  44. package/dist/workspace/scopedProjectContext.d.ts.map +1 -1
  45. package/dist/workspace/scopedProjectContext.js +3 -3
  46. package/dist/workspace/scopedProjectContext.js.map +1 -1
  47. package/package.json +7 -1
  48. package/dist/config.d.ts +0 -29
  49. package/dist/config.d.ts.map +0 -1
  50. package/dist/config.js +0 -111
  51. package/dist/config.js.map +0 -1
  52. package/dist/homeImageCache.d.ts +0 -264
  53. package/dist/homeImageCache.d.ts.map +0 -1
  54. package/dist/homeImageCache.js +0 -930
  55. package/dist/homeImageCache.js.map +0 -1
  56. package/dist/imagePortClaims.d.ts +0 -41
  57. package/dist/imagePortClaims.d.ts.map +0 -1
  58. package/dist/imagePortClaims.js +0 -337
  59. package/dist/imagePortClaims.js.map +0 -1
  60. package/dist/imageRescue.d.ts +0 -155
  61. package/dist/imageRescue.d.ts.map +0 -1
  62. package/dist/imageRescue.js +0 -847
  63. package/dist/imageRescue.js.map +0 -1
  64. package/dist/pathStyle.d.ts +0 -11
  65. package/dist/pathStyle.d.ts.map +0 -1
  66. package/dist/pathStyle.js +0 -61
  67. package/dist/pathStyle.js.map +0 -1
  68. package/dist/pharoLauncherMcpClient.d.ts +0 -17
  69. package/dist/pharoLauncherMcpClient.d.ts.map +0 -1
  70. package/dist/pharoLauncherMcpClient.js +0 -78
  71. package/dist/pharoLauncherMcpClient.js.map +0 -1
  72. package/dist/pharoLauncherProfile.d.ts +0 -31
  73. package/dist/pharoLauncherProfile.d.ts.map +0 -1
  74. package/dist/pharoLauncherProfile.js +0 -122
  75. package/dist/pharoLauncherProfile.js.map +0 -1
  76. package/dist/pharoMcpHealth.d.ts +0 -26
  77. package/dist/pharoMcpHealth.d.ts.map +0 -1
  78. package/dist/pharoMcpHealth.js +0 -97
  79. package/dist/pharoMcpHealth.js.map +0 -1
  80. package/dist/plexusHome.d.ts +0 -17
  81. package/dist/plexusHome.d.ts.map +0 -1
  82. package/dist/plexusHome.js +0 -30
  83. package/dist/plexusHome.js.map +0 -1
  84. package/dist/portClaims.d.ts +0 -116
  85. package/dist/portClaims.d.ts.map +0 -1
  86. package/dist/portClaims.js +0 -393
  87. package/dist/portClaims.js.map +0 -1
  88. package/dist/preparedImageCache.d.ts +0 -90
  89. package/dist/preparedImageCache.d.ts.map +0 -1
  90. package/dist/preparedImageCache.js +0 -237
  91. package/dist/preparedImageCache.js.map +0 -1
  92. package/dist/projectCleanup.d.ts +0 -59
  93. package/dist/projectCleanup.d.ts.map +0 -1
  94. package/dist/projectCleanup.js +0 -483
  95. package/dist/projectCleanup.js.map +0 -1
  96. package/dist/projectClose.d.ts +0 -35
  97. package/dist/projectClose.d.ts.map +0 -1
  98. package/dist/projectClose.js +0 -273
  99. package/dist/projectClose.js.map +0 -1
  100. package/dist/projectConfig.d.ts +0 -233
  101. package/dist/projectConfig.d.ts.map +0 -1
  102. package/dist/projectConfig.js +0 -1181
  103. package/dist/projectConfig.js.map +0 -1
  104. package/dist/projectGateway.d.ts +0 -80
  105. package/dist/projectGateway.d.ts.map +0 -1
  106. package/dist/projectGateway.js +0 -435
  107. package/dist/projectGateway.js.map +0 -1
  108. package/dist/projectImageMcpEndpoint.d.ts +0 -24
  109. package/dist/projectImageMcpEndpoint.d.ts.map +0 -1
  110. package/dist/projectImageMcpEndpoint.js +0 -79
  111. package/dist/projectImageMcpEndpoint.js.map +0 -1
  112. package/dist/projectLifecycle.d.ts +0 -428
  113. package/dist/projectLifecycle.d.ts.map +0 -1
  114. package/dist/projectLifecycle.js +0 -2147
  115. package/dist/projectLifecycle.js.map +0 -1
  116. package/dist/projectOpen.d.ts +0 -68
  117. package/dist/projectOpen.d.ts.map +0 -1
  118. package/dist/projectOpen.js +0 -1472
  119. package/dist/projectOpen.js.map +0 -1
  120. package/dist/projectRepositoryWorkspace.d.ts +0 -74
  121. package/dist/projectRepositoryWorkspace.d.ts.map +0 -1
  122. package/dist/projectRepositoryWorkspace.js +0 -553
  123. package/dist/projectRepositoryWorkspace.js.map +0 -1
  124. package/dist/projectStartupScript.d.ts +0 -74
  125. package/dist/projectStartupScript.d.ts.map +0 -1
  126. package/dist/projectStartupScript.js +0 -748
  127. package/dist/projectStartupScript.js.map +0 -1
  128. package/dist/projectState.d.ts +0 -315
  129. package/dist/projectState.d.ts.map +0 -1
  130. package/dist/projectState.js +0 -399
  131. package/dist/projectState.js.map +0 -1
  132. package/dist/runtimeIdentity.d.ts +0 -15
  133. package/dist/runtimeIdentity.d.ts.map +0 -1
  134. package/dist/runtimeIdentity.js +0 -25
  135. package/dist/runtimeIdentity.js.map +0 -1
  136. package/dist/scopedPharoLauncherServer.d.ts +0 -247
  137. package/dist/scopedPharoLauncherServer.d.ts.map +0 -1
  138. package/dist/scopedPharoLauncherServer.js +0 -1112
  139. package/dist/scopedPharoLauncherServer.js.map +0 -1
  140. package/dist/scopedProjectContext.d.ts +0 -169
  141. package/dist/scopedProjectContext.d.ts.map +0 -1
  142. package/dist/scopedProjectContext.js +0 -358
  143. package/dist/scopedProjectContext.js.map +0 -1
  144. package/dist/scopedTemplateCatalog.d.ts +0 -32
  145. package/dist/scopedTemplateCatalog.d.ts.map +0 -1
  146. package/dist/scopedTemplateCatalog.js +0 -316
  147. package/dist/scopedTemplateCatalog.js.map +0 -1
  148. package/dist/server.d.ts +0 -86
  149. package/dist/server.d.ts.map +0 -1
  150. package/dist/server.js +0 -357
  151. package/dist/server.js.map +0 -1
  152. package/dist/target.d.ts +0 -19
  153. package/dist/target.d.ts.map +0 -1
  154. package/dist/target.js +0 -2
  155. package/dist/target.js.map +0 -1
  156. package/dist/toolResultFormatting.d.ts +0 -8
  157. package/dist/toolResultFormatting.d.ts.map +0 -1
  158. package/dist/toolResultFormatting.js +0 -81
  159. package/dist/toolResultFormatting.js.map +0 -1
  160. package/dist/workspace/workspaceMcpConfig.d.ts +0 -51
  161. package/dist/workspace/workspaceMcpConfig.d.ts.map +0 -1
  162. package/dist/workspace/workspaceMcpConfig.js +0 -98
  163. package/dist/workspace/workspaceMcpConfig.js.map +0 -1
  164. package/dist/workspaceMcpConfig.d.ts +0 -51
  165. package/dist/workspaceMcpConfig.d.ts.map +0 -1
  166. package/dist/workspaceMcpConfig.js +0 -98
  167. package/dist/workspaceMcpConfig.js.map +0 -1
@@ -1,2147 +0,0 @@
1
- import fs from "node:fs";
2
- import path from "node:path";
3
- import { defaultImagePortClaimChecks, imagePortClaimsRootForConfig, } from "./imagePortClaims.js";
4
- import { rescueImage, } from "./imageRescue.js";
5
- import { loadProjectConfig, plexusProjectConfigFileName, projectConfigId, ProjectConfigError, resolveProjectRuntimePolicy, } from "./projectConfig.js";
6
- import { closeProject } from "./projectClose.js";
7
- import { cleanupProjectOwnedResources, } from "./projectCleanup.js";
8
- import { closeProjectGateway, ensureProjectGateway, projectGatewayStatus, } from "./projectGateway.js";
9
- import { inspectPortClaim, listPortClaims, releasePortClaim, } from "./portClaims.js";
10
- import { flushHomeImageCache, homeImageCacheManifestPath, homeImageCacheProfile, homeImageCacheRootPath, listHomeImageCacheManifests, planHomeImageCacheFlush, profileEnvironmentFromPaths, readHomeImageCacheManifest, resolvePlexusHomePath, } from "./homeImageCache.js";
11
- import { createStdioPharoLauncherMcpClient, } from "./pharoLauncherMcpClient.js";
12
- import { openProject, ProjectOpenError, } from "./projectOpen.js";
13
- import { inspectProjectImageRepositoryWorkspace, } from "./projectRepositoryWorkspace.js";
14
- import { defaultPlexusStateRoot, defaultTargetId, defaultWorkspaceId, loadProjectState, projectStateRootForConfig, projectStatePathForConfig, projectImageRepositoryWorkspaceStates, projectImageRepositoryWorkspaces, renderProjectImageName, runtimeStatusForImages, sanitizeRuntimeId, saveProjectState, } from "./projectState.js";
15
- import { describePharoLauncherMcpProfile, } from "./pharoLauncherProfile.js";
16
- import { buildScopedProjectContext, } from "./scopedProjectContext.js";
17
- import { plexusRuntimeIdentity, } from "./runtimeIdentity.js";
18
- function remoteWorkspaceTargetForInput(workspace, targetId) {
19
- return targetId
20
- ? workspace.targets?.find((candidate) => candidate.targetId === targetId)
21
- : undefined;
22
- }
23
- function remoteLifecycleMappingForWorkspace(remoteNode, workspace, workspaceId, targetId) {
24
- const target = remoteWorkspaceTargetForInput(workspace, targetId);
25
- if (targetId && workspace.targets && !target) {
26
- return undefined;
27
- }
28
- if (workspace.workspaceId !== workspaceId && !target) {
29
- return undefined;
30
- }
31
- return {
32
- remoteNode,
33
- workspace,
34
- ...(target ? { target } : {}),
35
- workspaceId,
36
- };
37
- }
38
- const defaultGatewayRouteControlMcpPath = "/control-mcp";
39
- const defaultPharoToolsDiscoveryTimeoutMs = 5_000;
40
- class ProjectLifecycleInputError extends Error {
41
- constructor(message) {
42
- super(message);
43
- this.name = "ProjectLifecycleInputError";
44
- }
45
- }
46
- function isObject(value) {
47
- return Boolean(value) && typeof value === "object" && !Array.isArray(value);
48
- }
49
- function isProjectImageMcpEndpoint(value) {
50
- return (isObject(value) &&
51
- value.transport === "http" &&
52
- typeof value.host === "string" &&
53
- typeof value.port === "number" &&
54
- Number.isInteger(value.port) &&
55
- typeof value.path === "string");
56
- }
57
- function requireString(input, key) {
58
- const value = input[key];
59
- if (typeof value !== "string" || value.length === 0) {
60
- throw new ProjectLifecycleInputError(`${key} is required`);
61
- }
62
- return value;
63
- }
64
- function optionalString(input, key) {
65
- const value = input[key];
66
- if (value === undefined) {
67
- return undefined;
68
- }
69
- if (typeof value !== "string" || value.length === 0) {
70
- throw new ProjectLifecycleInputError(`${key} must be a non-empty string`);
71
- }
72
- return value;
73
- }
74
- function optionalBoolean(input, key) {
75
- const value = input[key];
76
- if (value === undefined) {
77
- return false;
78
- }
79
- if (typeof value !== "boolean") {
80
- throw new ProjectLifecycleInputError(`${key} must be a boolean`);
81
- }
82
- return value;
83
- }
84
- function optionalBooleanValue(input, key) {
85
- const value = input[key];
86
- if (value === undefined) {
87
- return undefined;
88
- }
89
- if (typeof value !== "boolean") {
90
- throw new ProjectLifecycleInputError(`${key} must be a boolean`);
91
- }
92
- return value;
93
- }
94
- function optionalDisplayMode(input, key) {
95
- const value = input[key];
96
- if (value === undefined) {
97
- return undefined;
98
- }
99
- if (value === "headless" || value === "interactive") {
100
- return value;
101
- }
102
- throw new ProjectLifecycleInputError(`${key} must be headless or interactive`);
103
- }
104
- function optionalRepositoryWorkspaceCleanupPolicy(input) {
105
- const value = input.repositoryWorkspaceCleanupPolicy;
106
- if (value === undefined) {
107
- return undefined;
108
- }
109
- if (value === "preserve" ||
110
- value === "archive" ||
111
- value === "delete-disposable") {
112
- return value;
113
- }
114
- throw new ProjectLifecycleInputError("repositoryWorkspaceCleanupPolicy must be preserve, archive, or delete-disposable");
115
- }
116
- function optionalNumber(input, key) {
117
- const value = input[key];
118
- if (value === undefined) {
119
- return undefined;
120
- }
121
- if (typeof value !== "number" || !Number.isInteger(value)) {
122
- throw new ProjectLifecycleInputError(`${key} must be an integer`);
123
- }
124
- return value;
125
- }
126
- function optionalObject(input, key) {
127
- const value = input[key];
128
- if (value === undefined) {
129
- return {};
130
- }
131
- if (!isObject(value)) {
132
- throw new ProjectLifecycleInputError(`${key} must be an object`);
133
- }
134
- return value;
135
- }
136
- function numberArray(value, key) {
137
- if (value === undefined) {
138
- return undefined;
139
- }
140
- if (!Array.isArray(value) || !value.every(Number.isInteger)) {
141
- throw new ProjectLifecycleInputError(`${key} must be an array of integers`);
142
- }
143
- return value;
144
- }
145
- function stringArray(value, key) {
146
- if (value === undefined) {
147
- return undefined;
148
- }
149
- if (!Array.isArray(value) ||
150
- !value.every((item) => typeof item === "string" && item.length > 0)) {
151
- throw new ProjectLifecycleInputError(`${key} must be an array of non-empty strings`);
152
- }
153
- return value;
154
- }
155
- function optionalEntrySelection(input, key) {
156
- const value = input[key];
157
- if (value === undefined) {
158
- return undefined;
159
- }
160
- if (!isObject(value)) {
161
- throw new ProjectLifecycleInputError(`${key} must be an object`);
162
- }
163
- return {
164
- indexes: numberArray(value.indexes, `${key}.indexes`),
165
- entryReferences: stringArray(value.entryReferences, `${key}.entryReferences`),
166
- startIndex: optionalNumber(value, "startIndex"),
167
- endIndex: optionalNumber(value, "endIndex"),
168
- latestCount: optionalNumber(value, "latestCount"),
169
- };
170
- }
171
- function optionalRepositoryActions(input, key) {
172
- const value = input[key];
173
- if (value === undefined) {
174
- return undefined;
175
- }
176
- if (!Array.isArray(value)) {
177
- throw new ProjectLifecycleInputError(`${key} must be an array`);
178
- }
179
- return value.map((item, index) => {
180
- if (!isObject(item)) {
181
- throw new ProjectLifecycleInputError(`${key}[${index}] must be an object`);
182
- }
183
- const toolName = item.toolName;
184
- if (toolName !== undefined &&
185
- toolName !== "load_repository" &&
186
- toolName !== "edit_repository") {
187
- throw new ProjectLifecycleInputError(`${key}[${index}].toolName must be load_repository or edit_repository`);
188
- }
189
- return {
190
- label: optionalString(item, "label"),
191
- toolName: toolName,
192
- arguments: optionalObject(item, "arguments"),
193
- };
194
- });
195
- }
196
- function requireRescueOperation(input) {
197
- const value = input.operation;
198
- if (value === "snapshotSource" ||
199
- value === "plan" ||
200
- value === "prepareTarget" ||
201
- value === "applyPlan") {
202
- return value;
203
- }
204
- throw new ProjectLifecycleInputError("operation must be snapshotSource, plan, prepareTarget, or applyPlan");
205
- }
206
- function objectInput(input) {
207
- if (!isObject(input)) {
208
- return {};
209
- }
210
- return input;
211
- }
212
- function result(data) {
213
- return { ok: true, data };
214
- }
215
- function failure(error) {
216
- const diagnostics = {
217
- toolRuntime: plexusRuntimeIdentity(),
218
- ...(error instanceof ProjectConfigError
219
- ? {
220
- projectConfig: {
221
- issues: error.issues,
222
- },
223
- }
224
- : {}),
225
- ...(error instanceof ProjectOpenError
226
- ? {
227
- projectOpen: {
228
- statePath: error.result.statePath,
229
- failures: error.result.failures,
230
- images: error.result.state.images,
231
- },
232
- }
233
- : {}),
234
- };
235
- return {
236
- ok: false,
237
- error: error instanceof Error ? error.message : String(error),
238
- diagnostics,
239
- };
240
- }
241
- function routeCleanupResource(state) {
242
- return {
243
- kind: "route",
244
- status: "planned",
245
- id: state.targetId,
246
- projectId: state.projectId,
247
- workspaceId: state.workspaceId,
248
- targetId: state.targetId,
249
- };
250
- }
251
- function idempotentRouteCleanupReason(error) {
252
- const message = errorMessage(error);
253
- if (/\bfetch failed\b/i.test(message) ||
254
- /\bECONNREFUSED\b/i.test(message) ||
255
- /\bFailed to fetch\b/i.test(message) ||
256
- /\bNo route is registered\b/i.test(message)) {
257
- return `Route cleanup skipped because the route endpoint is already unreachable: ${message}`;
258
- }
259
- return undefined;
260
- }
261
- function assertLauncherOk(result, toolName) {
262
- if (result && result.ok === false) {
263
- throw new Error(`${toolName} returned ok: false`);
264
- }
265
- }
266
- function cacheEntryStatusFromReadResult(readResult) {
267
- const key = path.basename(path.dirname(readResult.manifestPath));
268
- if (readResult.status === "ok") {
269
- return {
270
- key: readResult.manifest.key,
271
- status: "ok",
272
- manifestPath: readResult.manifestPath,
273
- cacheImageName: readResult.manifest.cacheImageName,
274
- preparationStatus: readResult.manifest.pharoMcp.preparationStatus,
275
- supportStatus: readResult.manifest.pharoMcp.support.status,
276
- createdAt: readResult.manifest.createdAt,
277
- updatedAt: readResult.manifest.updatedAt,
278
- };
279
- }
280
- return {
281
- key,
282
- status: readResult.status,
283
- manifestPath: readResult.manifestPath,
284
- ...(readResult.status === "corrupt" ? { error: readResult.error } : {}),
285
- };
286
- }
287
- function unwrapToolLikeResult(value) {
288
- if (isObject(value) && typeof value.ok === "boolean") {
289
- if (value.ok === false) {
290
- throw new Error(typeof value.error === "string" ? value.error : "Tool call failed");
291
- }
292
- return value.data;
293
- }
294
- return value;
295
- }
296
- function textContent(value) {
297
- if (!isObject(value) || !Array.isArray(value.content)) {
298
- return undefined;
299
- }
300
- const item = value.content.find((candidate) => isObject(candidate) &&
301
- candidate.type === "text" &&
302
- typeof candidate.text === "string");
303
- return item?.text;
304
- }
305
- function decodeMcpToolResult(value) {
306
- const text = textContent(value);
307
- if (text === undefined) {
308
- return value;
309
- }
310
- try {
311
- return JSON.parse(text);
312
- }
313
- catch {
314
- return value;
315
- }
316
- }
317
- function lifecycleReferenceFromInput(input) {
318
- return {
319
- projectId: input.projectId,
320
- workspaceId: input.workspaceId,
321
- targetId: input.targetId,
322
- };
323
- }
324
- function lifecycleStatusFromRoute(route, includeDiagnostics = false) {
325
- if (!isObject(route)) {
326
- return includeDiagnostics ? { route } : {};
327
- }
328
- const statePath = typeof route.statePath === "string" ? route.statePath : undefined;
329
- const state = statePath ? loadProjectState(statePath) : undefined;
330
- const status = {
331
- projectId: typeof route.projectId === "string" ? route.projectId : state?.projectId,
332
- workspaceId: typeof route.workspaceId === "string"
333
- ? route.workspaceId
334
- : state?.workspaceId,
335
- targetId: typeof route.targetId === "string" ? route.targetId : state?.targetId,
336
- };
337
- if (!includeDiagnostics) {
338
- return status;
339
- }
340
- return {
341
- ...status,
342
- projectRoot: typeof route.projectRoot === "string" ? route.projectRoot : undefined,
343
- statePath,
344
- state,
345
- ...(state?.gateway ? { gateway: state.gateway } : {}),
346
- route,
347
- };
348
- }
349
- function errorMessage(error) {
350
- return error instanceof Error ? error.message : String(error);
351
- }
352
- function mergePortClaimChecks(options) {
353
- const defaults = defaultImagePortClaimChecks();
354
- return {
355
- isProcessAlive: options.checks?.isProcessAlive ?? defaults.isProcessAlive,
356
- isPortListening: options.checks?.isPortListening ?? defaults.isPortListening,
357
- };
358
- }
359
- function currentScopeMatchesClaim(claim, scope) {
360
- return (claim.projectId === scope.projectId &&
361
- claim.workspaceId === scope.workspaceId &&
362
- claim.targetId === scope.targetId);
363
- }
364
- function portClaimDiagnostic(claimsRoot, inspection, scope) {
365
- if (inspection.status === "unreadable") {
366
- return {
367
- claimsRoot,
368
- port: inspection.port,
369
- status: "unreadable",
370
- reason: inspection.reason,
371
- };
372
- }
373
- return {
374
- claimsRoot,
375
- port: inspection.port,
376
- status: inspection.status,
377
- record: inspection.record,
378
- ...(inspection.reason ? { reason: inspection.reason } : {}),
379
- ownedByCurrentScope: currentScopeMatchesClaim(inspection.record, scope),
380
- };
381
- }
382
- function addCurrentScopePortClaimDiagnostic(buckets, diagnostic) {
383
- if (diagnostic.status === "stale") {
384
- buckets.stale.push(diagnostic);
385
- return;
386
- }
387
- buckets.active.push(diagnostic);
388
- }
389
- function addForeignScopePortClaimDiagnostic(buckets, diagnostic, currentScopePorts) {
390
- if (!currentScopePorts.has(diagnostic.port)) {
391
- buckets.otherScopes.push(diagnostic);
392
- return;
393
- }
394
- if (diagnostic.status === "stale") {
395
- buckets.stale.push(diagnostic);
396
- return;
397
- }
398
- buckets.conflicts.push(diagnostic);
399
- }
400
- function addPortClaimDiagnostic(buckets, diagnostic, currentScopePorts) {
401
- if (diagnostic.ownedByCurrentScope) {
402
- addCurrentScopePortClaimDiagnostic(buckets, diagnostic);
403
- return;
404
- }
405
- addForeignScopePortClaimDiagnostic(buckets, diagnostic, currentScopePorts);
406
- }
407
- async function inspectClaimRoots(claimsRoots, checks, scope, currentScopePorts) {
408
- const active = [];
409
- const stale = [];
410
- const conflicts = [];
411
- const otherScopes = [];
412
- for (const claimsRoot of claimsRoots) {
413
- const claims = await listPortClaims({ claimsRoot });
414
- for (const claim of claims) {
415
- const inspection = await inspectPortClaim({
416
- claimsRoot,
417
- port: claim.assignedPort,
418
- checks,
419
- });
420
- if (inspection.status === "available") {
421
- continue;
422
- }
423
- const diagnostic = portClaimDiagnostic(claimsRoot, inspection, scope);
424
- addPortClaimDiagnostic({ active, stale, conflicts, otherScopes }, diagnostic, currentScopePorts);
425
- }
426
- }
427
- return {
428
- roots: claimsRoots,
429
- active,
430
- stale,
431
- conflicts,
432
- otherScopes,
433
- };
434
- }
435
- function configuredClaimRoots(projectRoot, config, state) {
436
- return [
437
- imagePortClaimsRootForConfig(projectRoot, config),
438
- state?.gateway?.claim?.claimsRoot,
439
- ].filter((value, index, values) => typeof value === "string" && values.indexOf(value) === index);
440
- }
441
- function projectDiagnostics(config, state) {
442
- return {
443
- declaredImageCount: config.images.length,
444
- activeImageCount: config.images.filter((image) => image.active).length,
445
- runtimeImageCount: state?.images.length ?? 0,
446
- };
447
- }
448
- function remoteTopologyDiagnostics(config, runtime) {
449
- const remoteNodes = runtime.remoteNodes ?? [];
450
- return {
451
- nodeId: runtime.nodeId ?? projectConfigId(config),
452
- policy: "flat-tree",
453
- status: remoteNodes.length === 0 ? "local-only" : "flat",
454
- remoteNodeIds: remoteNodes.map((remoteNode) => remoteNode.id),
455
- remoteNodes: remoteNodes.map((remoteNode) => ({
456
- id: remoteNode.id,
457
- ...(remoteNode.parentNodeId
458
- ? { parentNodeId: remoteNode.parentNodeId }
459
- : {}),
460
- mappedWorkspaceIds: remoteNode.workspaces?.map((workspace) => workspace.workspaceId) ?? [],
461
- })),
462
- };
463
- }
464
- function imagePortPolicyDiagnostics(runtime, stateRoot, effectiveClaimsRoot) {
465
- const coordination = runtime.imagePorts.coordination;
466
- return {
467
- allocation: runtime.imagePorts.allocation,
468
- range: runtime.imagePorts.range,
469
- coordinationMode: coordination.mode,
470
- ...(coordination.root ? { configuredRoot: coordination.root } : {}),
471
- ...(effectiveClaimsRoot ? { effectiveClaimsRoot } : {}),
472
- projectStateRoot: stateRoot,
473
- basis: effectiveClaimsRoot ? "host-local-claims" : "project-state",
474
- };
475
- }
476
- function imagePortCoordinationDiagnostics(projectRoot, stateRoot, config) {
477
- const coordination = resolveProjectRuntimePolicy(config).imagePorts.coordination;
478
- if (coordination.mode === "host-local") {
479
- const claimsRoot = imagePortClaimsRootForConfig(projectRoot, config);
480
- return {
481
- mode: "host-local",
482
- basis: "host-local-claims",
483
- message: "Image MCP ports are coordinated by host-local port claims across PLexus projects on this host.",
484
- ...(claimsRoot ? { claimsRoot } : {}),
485
- };
486
- }
487
- return {
488
- mode: "project-state",
489
- basis: "project-state-scanning",
490
- stateRoot,
491
- message: "Image MCP ports are coordinated by scanning PLexus project state; this only protects workspaces sharing this state root.",
492
- };
493
- }
494
- function agentAccessDiagnostics(gateway, reconciliation) {
495
- if (reconciliation?.status === "dead") {
496
- return {
497
- expectedSurface: "pharo_gateway",
498
- gatewayRouted: false,
499
- portsHiddenFromAgents: true,
500
- reason: "The scoped pharo_gateway is expected, but the recorded project-local gateway is dead. Reopen the project instead of using direct image ports.",
501
- };
502
- }
503
- return {
504
- expectedSurface: "pharo_gateway",
505
- gatewayRouted: Boolean(gateway.endpoint),
506
- portsHiddenFromAgents: true,
507
- reason: "Normal agent Pharo MCP calls should use pharo_gateway imageId routing; image MCP ports are diagnostics only.",
508
- };
509
- }
510
- function repositoryWorkspaceCleanupDiagnostic(workspace, inspection) {
511
- const lastDecision = workspace.cleanupState;
512
- if (!inspection) {
513
- return {
514
- defaultPolicy: "preserve",
515
- destructivePolicyRequired: true,
516
- reviewRequired: false,
517
- recommendedAction: "materialize",
518
- message: "Repository workspace is planned; destructive cleanup is unavailable until it is materialized.",
519
- ...(lastDecision ? { lastDecision } : {}),
520
- };
521
- }
522
- if (!inspection.exists) {
523
- return {
524
- defaultPolicy: "preserve",
525
- destructivePolicyRequired: true,
526
- reviewRequired: true,
527
- recommendedAction: "materialize",
528
- message: "Repository workspace path is missing.",
529
- ...(lastDecision ? { lastDecision } : {}),
530
- };
531
- }
532
- if (!inspection.isGitRepository) {
533
- return {
534
- defaultPolicy: "preserve",
535
- destructivePolicyRequired: true,
536
- reviewRequired: true,
537
- recommendedAction: "repair",
538
- message: "Repository workspace path exists but is not a Git repository.",
539
- ...(lastDecision ? { lastDecision } : {}),
540
- };
541
- }
542
- if (inspection.dirtyState === "dirty") {
543
- return {
544
- defaultPolicy: "preserve",
545
- destructivePolicyRequired: true,
546
- reviewRequired: true,
547
- recommendedAction: "review",
548
- message: "Repository workspace has uncommitted changes; preserve, archive, or hand off before deletion.",
549
- ...(lastDecision ? { lastDecision } : {}),
550
- };
551
- }
552
- return {
553
- defaultPolicy: "preserve",
554
- destructivePolicyRequired: true,
555
- reviewRequired: false,
556
- recommendedAction: "none",
557
- message: "Repository workspace is clean; destructive cleanup still requires an explicit policy.",
558
- ...(lastDecision ? { lastDecision } : {}),
559
- };
560
- }
561
- function liveRepositoryWorkspaceState(workspace, inspection) {
562
- if (!inspection) {
563
- return workspace;
564
- }
565
- return {
566
- ...workspace,
567
- path: inspection.path,
568
- dirtyState: inspection.dirtyState,
569
- diagnostics: [...workspace.diagnostics, ...inspection.diagnostics],
570
- ...(inspection.branch ? { branch: inspection.branch } : {}),
571
- ...(inspection.currentCommit
572
- ? { currentCommit: inspection.currentCommit }
573
- : {}),
574
- };
575
- }
576
- function repositoryWorkspaceDiagnostics(projectRoot, config, state, scope) {
577
- return config.images
578
- .flatMap((imageConfig) => {
579
- const imageState = state?.images.find((image) => image.id === imageConfig.id);
580
- const context = {
581
- projectId: scope.projectId,
582
- projectName: config.name,
583
- workspaceId: scope.workspaceId,
584
- targetId: scope.targetId,
585
- imageId: imageConfig.id,
586
- };
587
- const workspaces = imageState
588
- ? projectImageRepositoryWorkspaces(imageState)
589
- : projectImageRepositoryWorkspaceStates(imageConfig, context);
590
- return workspaces.map((workspace) => {
591
- const inspection = imageState
592
- ? inspectProjectImageRepositoryWorkspace({
593
- projectRoot,
594
- imageState,
595
- workspace,
596
- })
597
- : undefined;
598
- const liveWorkspace = liveRepositoryWorkspaceState(workspace, inspection);
599
- return {
600
- imageId: imageConfig.id,
601
- imageName: imageState?.imageName ??
602
- renderProjectImageName(imageConfig.imageName, context),
603
- status: imageState?.status ?? "declared",
604
- workspace: liveWorkspace,
605
- cleanup: repositoryWorkspaceCleanupDiagnostic(liveWorkspace, inspection),
606
- };
607
- });
608
- })
609
- .filter((item) => item !== undefined);
610
- }
611
- function dependencyRepositoryDetachDiagnostics(state) {
612
- return (state?.images ?? [])
613
- .filter((image) => image.dependencyRepositoryDetach !== undefined)
614
- .map((image) => ({
615
- imageId: image.id,
616
- imageName: image.imageName,
617
- status: image.status,
618
- detach: image.dependencyRepositoryDetach,
619
- }));
620
- }
621
- function imageRecoveryDiagnostics(input) {
622
- return (input.state?.images ?? [])
623
- .filter((image) => image.status === "failed")
624
- .map((image) => {
625
- const actionBase = {
626
- projectPath: input.projectRoot,
627
- stateRoot: input.stateRoot,
628
- workspaceId: input.workspaceId,
629
- sourceImageId: image.id,
630
- };
631
- return {
632
- imageId: image.id,
633
- imageName: image.imageName,
634
- status: image.status,
635
- message: `Image ${image.id} is failed; use scoped rescue before raw cleanup.`,
636
- paths: {
637
- ...(image.imagePath ? { imagePath: image.imagePath } : {}),
638
- ...(image.imageDirectoryPath
639
- ? { imageDirectoryPath: image.imageDirectoryPath }
640
- : {}),
641
- ...(image.changesPath ? { changesPath: image.changesPath } : {}),
642
- ...(image.localDirectoryPath
643
- ? { localDirectoryPath: image.localDirectoryPath }
644
- : {}),
645
- ...(image.ombuDirectoryPath
646
- ? { ombuDirectoryPath: image.ombuDirectoryPath }
647
- : {}),
648
- },
649
- actions: [
650
- {
651
- operation: "plan",
652
- toolName: "plexus_rescue_image",
653
- arguments: {
654
- ...actionBase,
655
- operation: "plan",
656
- },
657
- },
658
- {
659
- operation: "prepareTarget",
660
- toolName: "plexus_rescue_image",
661
- arguments: {
662
- ...actionBase,
663
- operation: "prepareTarget",
664
- },
665
- },
666
- ],
667
- };
668
- });
669
- }
670
- function imageMcpPorts(state) {
671
- return (state?.images ?? []).map((image) => ({
672
- imageId: image.id,
673
- imageName: image.imageName,
674
- ...(image.displayMode ? { displayMode: image.displayMode } : {}),
675
- ...(image.assignedPort !== undefined ? { port: image.assignedPort } : {}),
676
- ...(image.mcpEndpoint !== undefined ? { mcpEndpoint: image.mcpEndpoint } : {}),
677
- routingMode: image.mcpEndpoint !== undefined
678
- ? "endpoint"
679
- : image.assignedPort !== undefined
680
- ? "fixed-port"
681
- : "none",
682
- status: image.status,
683
- ...(image.pid !== undefined ? { pid: image.pid } : {}),
684
- }));
685
- }
686
- function registeredRouteStatePath(route) {
687
- return isObject(route) && typeof route.statePath === "string"
688
- ? route.statePath
689
- : undefined;
690
- }
691
- function sameResolvedPath(left, right) {
692
- return (left !== undefined &&
693
- right !== undefined &&
694
- path.resolve(left) === path.resolve(right));
695
- }
696
- function routeTableDiagnostics(targetId, route, routeError, expectedStatePath, gatewayReconciliation) {
697
- if (!targetId) {
698
- return {
699
- status: "not-configured",
700
- routableImages: [],
701
- };
702
- }
703
- if (gatewayReconciliation?.status === "dead") {
704
- return {
705
- targetId,
706
- status: "gateway-dead",
707
- routableImages: [],
708
- error: gatewayReconciliation.reason,
709
- };
710
- }
711
- if (routeError) {
712
- const message = errorMessage(routeError);
713
- return {
714
- targetId,
715
- status: message.includes("No route is registered")
716
- ? "missing"
717
- : "unavailable",
718
- routableImages: [],
719
- error: message,
720
- };
721
- }
722
- if (!isObject(route)) {
723
- return {
724
- targetId,
725
- status: "not-configured",
726
- routableImages: [],
727
- };
728
- }
729
- const images = Array.isArray(route.images) ? route.images : [];
730
- const statePath = registeredRouteStatePath(route);
731
- const statePathMismatch = statePath !== undefined &&
732
- expectedStatePath !== undefined &&
733
- !sameResolvedPath(statePath, expectedStatePath);
734
- const routableImages = images
735
- .filter(isObject)
736
- .map((image) => {
737
- const mcpEndpoint = isProjectImageMcpEndpoint(image.mcpEndpoint)
738
- ? image.mcpEndpoint
739
- : undefined;
740
- const routingMode = mcpEndpoint
741
- ? "endpoint"
742
- : typeof image.port === "number"
743
- ? "fixed-port"
744
- : "none";
745
- return {
746
- imageId: typeof image.id === "string" ? image.id : "",
747
- ...(typeof image.port === "number" ? { port: image.port } : {}),
748
- ...(mcpEndpoint ? { mcpEndpoint } : {}),
749
- routingMode,
750
- ...(typeof image.status === "string" ? { status: image.status } : {}),
751
- ...(statePathMismatch
752
- ? {
753
- routable: {
754
- ok: false,
755
- code: "image_unavailable",
756
- message: "Registered gateway route uses a different PLexus runtime state path",
757
- },
758
- }
759
- : "routable" in image
760
- ? { routable: image.routable }
761
- : {}),
762
- };
763
- });
764
- return {
765
- targetId,
766
- status: statePathMismatch ? "unavailable" : "registered",
767
- ...(statePath ? { statePath } : {}),
768
- ...(statePathMismatch && expectedStatePath ? { expectedStatePath } : {}),
769
- ...(statePathMismatch
770
- ? {
771
- error: `Registered gateway route state path ${statePath} does not match ` +
772
- `selected lifecycle state path ${expectedStatePath}`,
773
- }
774
- : {}),
775
- routableImages,
776
- };
777
- }
778
- function gatewayRepairAffordance(input) {
779
- return {
780
- allowed: true,
781
- toolName: "plexus_project_open",
782
- arguments: {
783
- projectPath: input.projectRoot,
784
- stateRoot: input.stateRoot,
785
- workspaceId: input.workspaceId,
786
- targetId: input.targetId,
787
- },
788
- reason: "Reopen the scoped project to start a fresh project-local gateway and re-register routes.",
789
- };
790
- }
791
- function gatewayWithoutRuntimeIdentity(gateway) {
792
- if (gateway.mode !== "project-local" || !gateway.managedByProject) {
793
- return gateway;
794
- }
795
- const result = { ...gateway };
796
- delete result.endpoint;
797
- delete result.controlEndpoint;
798
- delete result.pid;
799
- delete result.claim;
800
- return result;
801
- }
802
- function staleGatewayRuntimeIdentity(stale) {
803
- return {
804
- ...(stale.endpoint ? { endpoint: stale.endpoint } : {}),
805
- ...(stale.controlEndpoint
806
- ? { controlEndpoint: stale.controlEndpoint }
807
- : {}),
808
- ...(stale.port !== undefined ? { port: stale.port } : {}),
809
- ...(stale.pid !== undefined ? { pid: stale.pid } : {}),
810
- ...(stale.claim ? { claim: stale.claim } : {}),
811
- };
812
- }
813
- function staleGatewayDiagnostic(reconciliation, repair) {
814
- const stale = reconciliation.staleGateway;
815
- return {
816
- mode: stale.mode,
817
- status: "dead",
818
- health: "degraded",
819
- reason: reconciliation.reason,
820
- host: stale.host,
821
- portRange: stale.portRange,
822
- managedByProject: stale.managedByProject,
823
- stale: staleGatewayRuntimeIdentity(stale),
824
- repair,
825
- };
826
- }
827
- function gatewayDiagnosticStatus(gateway) {
828
- if (gateway.mode === "shared") {
829
- return "shared";
830
- }
831
- return gateway.endpoint && gateway.controlEndpoint ? "running" : "not-started";
832
- }
833
- function gatewayDiagnosticHealth(status) {
834
- return status === "not-started" ? "unknown" : "operational";
835
- }
836
- function gatewayDiagnosticReason(status) {
837
- return status === "not-started"
838
- ? "No project-local gateway endpoint is recorded for this scope yet."
839
- : "Gateway state is available for this scope.";
840
- }
841
- function gatewayDiagnostic(gateway, reconciliation, repair) {
842
- if (reconciliation) {
843
- return staleGatewayDiagnostic(reconciliation, repair);
844
- }
845
- const status = gatewayDiagnosticStatus(gateway);
846
- return {
847
- mode: gateway.mode,
848
- status,
849
- health: gatewayDiagnosticHealth(status),
850
- reason: gatewayDiagnosticReason(status),
851
- endpoint: gateway.endpoint,
852
- controlEndpoint: gateway.controlEndpoint,
853
- host: gateway.host,
854
- port: gateway.port,
855
- portRange: gateway.portRange,
856
- managedByProject: gateway.managedByProject,
857
- pid: gateway.pid,
858
- ...(status === "not-started" ? { repair } : {}),
859
- };
860
- }
861
- function expectedPortClaims(portClaims) {
862
- return new Set(portClaims.active.map((claim) => claim.port));
863
- }
864
- function currentScopeClaimPorts(config, state, gateway) {
865
- const ports = new Set();
866
- if (gateway.port !== undefined) {
867
- ports.add(gateway.port);
868
- }
869
- if (gateway.claim?.assignedPort !== undefined) {
870
- ports.add(gateway.claim.assignedPort);
871
- }
872
- for (const image of state?.images ?? []) {
873
- if (image.assignedPort !== undefined) {
874
- ports.add(image.assignedPort);
875
- }
876
- }
877
- for (const image of config.images) {
878
- if (image.mcp.port !== undefined) {
879
- ports.add(image.mcp.port);
880
- }
881
- }
882
- return ports;
883
- }
884
- async function conflictingListenerDiagnostics(state, gateway, portClaims, checks) {
885
- const ownedClaimPorts = expectedPortClaims(portClaims);
886
- const diagnostics = [];
887
- for (const image of state?.images ?? []) {
888
- if (image.assignedPort === undefined) {
889
- continue;
890
- }
891
- const listening = Boolean(await checks.isPortListening?.(image.assignedPort));
892
- if (listening &&
893
- image.status !== "running" &&
894
- !ownedClaimPorts.has(image.assignedPort)) {
895
- diagnostics.push({
896
- port: image.assignedPort,
897
- purpose: "image-mcp",
898
- imageId: image.id,
899
- expectedOwner: `image ${image.id}`,
900
- message: `Image MCP port ${image.assignedPort} has a listener but the ` +
901
- `project image ${image.id} is ${image.status} and has no active owned claim.`,
902
- });
903
- }
904
- }
905
- if (gateway.port !== undefined) {
906
- const listening = Boolean(await checks.isPortListening?.(gateway.port));
907
- if (listening &&
908
- gateway.managedByProject &&
909
- !ownedClaimPorts.has(gateway.port)) {
910
- diagnostics.push({
911
- port: gateway.port,
912
- purpose: "gateway",
913
- expectedOwner: "project-local gateway",
914
- message: `Gateway port ${gateway.port} has a listener but no active owned claim.`,
915
- });
916
- }
917
- }
918
- return diagnostics;
919
- }
920
- async function reconcileDeadProjectGatewayState(input) {
921
- const stateGateway = input.state?.gateway;
922
- const gateway = stateGateway ?? input.gateway;
923
- if (!input.state ||
924
- !gateway ||
925
- gateway.mode !== "project-local" ||
926
- !gateway.managedByProject) {
927
- return undefined;
928
- }
929
- const runtimeStateNeedsGateway = input.state.runtimeStatus === "running" ||
930
- runtimeStatusForImages(input.state.images) === "running" ||
931
- stateHasRunningRoutableImage(input.state);
932
- if (!stateGateway && !runtimeStateNeedsGateway) {
933
- return undefined;
934
- }
935
- const port = gateway.port ?? gateway.claim?.assignedPort;
936
- const portListening = port === undefined ? false : Boolean(await input.checks.isPortListening?.(port));
937
- let claimInspection;
938
- if (gateway.claim) {
939
- claimInspection = await inspectPortClaim({
940
- claimsRoot: gateway.claim.claimsRoot,
941
- port: gateway.claim.assignedPort,
942
- checks: input.checks,
943
- });
944
- }
945
- const claimShowsDeadProcess = claimInspection?.status === "stale" &&
946
- claimInspection.reason === "process-dead";
947
- const claimMissingOrStale = claimInspection?.status === "available" ||
948
- claimInspection?.status === "stale";
949
- const gatewayIsDead = !portListening &&
950
- (claimShowsDeadProcess ||
951
- (gateway.pid === undefined && port !== undefined) ||
952
- claimMissingOrStale);
953
- if (!gatewayIsDead) {
954
- return undefined;
955
- }
956
- let releasedClaim = false;
957
- if (stateGateway?.claim) {
958
- const release = await releasePortClaim({
959
- claimsRoot: stateGateway.claim.claimsRoot,
960
- claim: {
961
- claimId: stateGateway.claim.claimId,
962
- assignedPort: stateGateway.claim.assignedPort,
963
- },
964
- });
965
- releasedClaim = release.released;
966
- }
967
- if (stateGateway) {
968
- delete input.state.gateway;
969
- input.state.updatedAt = input.now().toISOString();
970
- saveProjectState(input.statePath, input.state);
971
- }
972
- return {
973
- status: "dead",
974
- reason: "Recorded project-local gateway state is dead: the owned gateway port is not listening and its managed claim is stale or missing.",
975
- staleGateway: gateway,
976
- releasedClaim,
977
- };
978
- }
979
- function runtimeDiagnostics(state, gateway, portClaims, conflictingListeners, routeTable, gatewayReconciliation) {
980
- if (!state) {
981
- return {
982
- status: "not-opened",
983
- health: "unknown",
984
- reason: "No project runtime state exists for this workspace yet.",
985
- };
986
- }
987
- if (gatewayReconciliation?.status === "dead") {
988
- return {
989
- status: "degraded",
990
- health: "degraded",
991
- reason: "Runtime state exists, but the recorded project-local gateway is dead. Reopen the project to repair gateway routing.",
992
- };
993
- }
994
- if (portClaims.stale.length > 0 ||
995
- portClaims.conflicts.length > 0 ||
996
- conflictingListeners.length > 0 ||
997
- routeTable.status === "missing" ||
998
- routeTable.status === "unavailable" ||
999
- routeTable.status === "gateway-dead" ||
1000
- !gateway.endpoint ||
1001
- !gateway.controlEndpoint) {
1002
- return {
1003
- status: "degraded",
1004
- health: "degraded",
1005
- reason: "Runtime state exists, but diagnostics found stale claims, conflicts, route-table gaps, or incomplete gateway endpoints.",
1006
- };
1007
- }
1008
- if (state.images.length === 0 && runtimeStatusForImages(state.images) === "idle") {
1009
- return {
1010
- status: "idle",
1011
- health: "operational",
1012
- reason: "Runtime scope, gateway endpoints, and route table are valid; no images are declared for this project.",
1013
- };
1014
- }
1015
- return {
1016
- status: "operational",
1017
- health: "operational",
1018
- reason: "Runtime scope has valid gateway and route diagnostics.",
1019
- };
1020
- }
1021
- export class HttpGatewayRouteRegistry {
1022
- url;
1023
- timeoutMs;
1024
- fetchFn;
1025
- constructor(options = {}) {
1026
- const host = options.host ?? "127.0.0.1";
1027
- const port = options.port ?? 7331;
1028
- const mcpPath = options.path ?? defaultGatewayRouteControlMcpPath;
1029
- this.url = options.url ?? `http://${host}:${port}${mcpPath}`;
1030
- this.timeoutMs = options.timeoutMs ?? 10_000;
1031
- this.fetchFn = options.fetch ?? fetch;
1032
- }
1033
- registerProjectRoute(input) {
1034
- return this.callTool("plexus_gateway_register_target", input);
1035
- }
1036
- unregisterProjectRoute(input) {
1037
- return this.callTool("plexus_gateway_unregister_target", input);
1038
- }
1039
- getRouteStatus(input) {
1040
- return this.callTool("plexus_gateway_status", input);
1041
- }
1042
- async callTool(name, argumentsValue) {
1043
- const controller = new AbortController();
1044
- const timeout = setTimeout(() => controller.abort(), this.timeoutMs);
1045
- try {
1046
- const response = await this.fetchFn(this.url, {
1047
- method: "POST",
1048
- headers: {
1049
- accept: "application/json, text/event-stream",
1050
- "content-type": "application/json",
1051
- },
1052
- body: JSON.stringify({
1053
- jsonrpc: "2.0",
1054
- id: `plexus-core-${Date.now()}`,
1055
- method: "tools/call",
1056
- params: {
1057
- name,
1058
- arguments: argumentsValue,
1059
- },
1060
- }),
1061
- signal: controller.signal,
1062
- });
1063
- if (!response.ok) {
1064
- throw new Error(`Gateway MCP request failed with HTTP ${response.status}`);
1065
- }
1066
- const payload = (await response.json());
1067
- if (!isObject(payload)) {
1068
- throw new Error("Gateway MCP response was not a JSON object");
1069
- }
1070
- if ("error" in payload) {
1071
- throw new Error(JSON.stringify(payload.error));
1072
- }
1073
- return unwrapToolLikeResult(decodeMcpToolResult(payload.result));
1074
- }
1075
- finally {
1076
- clearTimeout(timeout);
1077
- }
1078
- }
1079
- }
1080
- export class HttpProjectLifecycleClient {
1081
- url;
1082
- timeoutMs;
1083
- fetchFn;
1084
- constructor(options) {
1085
- this.url = options.url;
1086
- this.timeoutMs = options.timeoutMs ?? 10_000;
1087
- this.fetchFn = options.fetch ?? fetch;
1088
- }
1089
- async callTool(name, argumentsValue) {
1090
- const controller = new AbortController();
1091
- const timeout = setTimeout(() => controller.abort(), this.timeoutMs);
1092
- try {
1093
- const response = await this.fetchFn(this.url, {
1094
- method: "POST",
1095
- headers: {
1096
- accept: "application/json, text/event-stream",
1097
- "content-type": "application/json",
1098
- },
1099
- body: JSON.stringify({
1100
- jsonrpc: "2.0",
1101
- id: `plexus-project-${Date.now()}`,
1102
- method: "tools/call",
1103
- params: {
1104
- name,
1105
- arguments: argumentsValue,
1106
- },
1107
- }),
1108
- signal: controller.signal,
1109
- });
1110
- if (!response.ok) {
1111
- throw new Error(`Remote project MCP request failed with HTTP ${response.status}`);
1112
- }
1113
- const payload = (await response.json());
1114
- if (!isObject(payload)) {
1115
- throw new Error("Remote project MCP response was not a JSON object");
1116
- }
1117
- if ("error" in payload) {
1118
- throw new Error(JSON.stringify(payload.error));
1119
- }
1120
- const decoded = decodeMcpToolResult(payload.result);
1121
- if (isObject(decoded) && typeof decoded.ok === "boolean") {
1122
- return decoded;
1123
- }
1124
- return {
1125
- ok: true,
1126
- data: decoded,
1127
- };
1128
- }
1129
- finally {
1130
- clearTimeout(timeout);
1131
- }
1132
- }
1133
- }
1134
- function gatewayHasExplicitPharoTools(gateway) {
1135
- if (gateway?.pharoTools !== undefined) {
1136
- return true;
1137
- }
1138
- const value = gateway?.env?.PLEXUS_PHARO_TOOLS_JSON;
1139
- if (value === undefined || value.trim().length === 0) {
1140
- return false;
1141
- }
1142
- try {
1143
- const parsed = JSON.parse(value);
1144
- return Array.isArray(parsed) && parsed.length > 0;
1145
- }
1146
- catch {
1147
- return true;
1148
- }
1149
- }
1150
- function imageMcpEndpointForToolDiscovery(image) {
1151
- if (image.status !== "running") {
1152
- return undefined;
1153
- }
1154
- if (image.mcpEndpoint) {
1155
- return image.mcpEndpoint;
1156
- }
1157
- if (image.assignedPort !== undefined) {
1158
- return {
1159
- transport: "http",
1160
- host: "127.0.0.1",
1161
- port: image.assignedPort,
1162
- path: "/",
1163
- };
1164
- }
1165
- return undefined;
1166
- }
1167
- function stateHasRunningRoutableImage(state) {
1168
- return state.images.some((image) => image.status === "running" &&
1169
- (image.mcpEndpoint !== undefined || image.assignedPort !== undefined));
1170
- }
1171
- function hostForUrl(host) {
1172
- return host.includes(":") && !host.startsWith("[") ? `[${host}]` : host;
1173
- }
1174
- function imageMcpEndpointUrl(endpoint) {
1175
- return `http://${hostForUrl(endpoint.host)}:${endpoint.port}${endpoint.path}`;
1176
- }
1177
- function remoteGatewayEndpointFromUrl(value) {
1178
- const url = new URL(value);
1179
- if (url.protocol !== "http:") {
1180
- throw new ProjectLifecycleInputError(`Remote gateway MCP URL must use http for PLexus gateway forwarding: ${value}`);
1181
- }
1182
- const port = url.port ? Number(url.port) : 80;
1183
- if (!Number.isInteger(port) || port < 1 || port > 65_535) {
1184
- throw new ProjectLifecycleInputError(`Remote gateway MCP URL must include a valid port: ${value}`);
1185
- }
1186
- return {
1187
- transport: "http",
1188
- host: url.hostname,
1189
- port,
1190
- path: url.pathname || "/",
1191
- };
1192
- }
1193
- function toolFromMcpListItem(value, index) {
1194
- if (!isObject(value) || typeof value.name !== "string") {
1195
- throw new Error(`MCP tools/list returned an invalid tool at index ${index}`);
1196
- }
1197
- if (!isObject(value.inputSchema)) {
1198
- throw new Error(`MCP tools/list returned tool ${value.name} without an inputSchema object`);
1199
- }
1200
- return value;
1201
- }
1202
- async function fetchPharoMcpTools(options) {
1203
- const controller = new AbortController();
1204
- const timeout = setTimeout(() => controller.abort(), options.timeoutMs);
1205
- try {
1206
- const response = await options.fetchFn(imageMcpEndpointUrl(options.endpoint), {
1207
- method: "POST",
1208
- headers: {
1209
- accept: "application/json, text/event-stream",
1210
- "content-type": "application/json",
1211
- },
1212
- body: JSON.stringify({
1213
- jsonrpc: "2.0",
1214
- id: `plexus-tools-list-${Date.now()}`,
1215
- method: "tools/list",
1216
- }),
1217
- signal: controller.signal,
1218
- });
1219
- if (!response.ok) {
1220
- throw new Error(`MCP tools/list failed with HTTP ${response.status}`);
1221
- }
1222
- const payload = (await response.json());
1223
- if (!isObject(payload)) {
1224
- throw new Error("MCP tools/list response was not a JSON object");
1225
- }
1226
- if ("error" in payload) {
1227
- throw new Error(JSON.stringify(payload.error));
1228
- }
1229
- const result = payload.result;
1230
- if (!isObject(result) || !Array.isArray(result.tools)) {
1231
- throw new Error("MCP tools/list response did not include result.tools");
1232
- }
1233
- return result.tools.map((tool, index) => toolFromMcpListItem(tool, index));
1234
- }
1235
- finally {
1236
- clearTimeout(timeout);
1237
- }
1238
- }
1239
- async function discoverPharoMcpToolsFromRunningImages(options) {
1240
- const errors = [];
1241
- let attempted = false;
1242
- for (const image of options.state.images) {
1243
- const endpoint = imageMcpEndpointForToolDiscovery(image);
1244
- if (!endpoint) {
1245
- continue;
1246
- }
1247
- attempted = true;
1248
- try {
1249
- const tools = await fetchPharoMcpTools({
1250
- endpoint,
1251
- fetchFn: options.fetchFn,
1252
- timeoutMs: options.timeoutMs ?? defaultPharoToolsDiscoveryTimeoutMs,
1253
- });
1254
- if (tools.length > 0) {
1255
- return tools;
1256
- }
1257
- errors.push(`${image.id}: MCP tools/list returned no tools`);
1258
- }
1259
- catch (error) {
1260
- errors.push(`${image.id}: ${error instanceof Error ? error.message : String(error)}`);
1261
- }
1262
- }
1263
- if (attempted) {
1264
- throw new Error(`Unable to discover Pharo MCP tools from running project images: ${errors.join("; ")}`);
1265
- }
1266
- return undefined;
1267
- }
1268
- function remoteLifecycleMappingForInput(config, projectRoot, input) {
1269
- const runtime = resolveProjectRuntimePolicy(config);
1270
- const remoteNodes = runtime.remoteNodes ?? [];
1271
- if (remoteNodes.length === 0) {
1272
- return undefined;
1273
- }
1274
- const workspaceId = input.workspaceId
1275
- ? sanitizeRuntimeId(input.workspaceId)
1276
- : defaultWorkspaceId(projectRoot);
1277
- for (const remoteNode of remoteNodes) {
1278
- for (const workspace of remoteNode.workspaces ?? []) {
1279
- const mapping = remoteLifecycleMappingForWorkspace(remoteNode, workspace, workspaceId, input.targetId);
1280
- if (mapping) {
1281
- return mapping;
1282
- }
1283
- }
1284
- }
1285
- return undefined;
1286
- }
1287
- function remoteLifecycleArguments(input, mapping) {
1288
- const projectPath = mapping.workspace?.remoteProjectPath ?? input.projectPath;
1289
- const workspaceId = mapping.workspace?.remoteWorkspaceId ??
1290
- input.workspaceId ??
1291
- mapping.workspaceId;
1292
- const targetId = mapping.target?.remoteTargetId ?? input.targetId;
1293
- return Object.fromEntries(Object.entries({
1294
- ...input,
1295
- projectPath,
1296
- stateRoot: undefined,
1297
- workspaceId,
1298
- targetId,
1299
- }).filter(([, value]) => value !== undefined));
1300
- }
1301
- function hostRemoteRouteContext(input, mapping) {
1302
- const projectRoot = path.resolve(input.projectPath);
1303
- const config = loadProjectConfig(projectRoot);
1304
- const projectId = projectConfigId(config);
1305
- const workspaceId = mapping.workspaceId;
1306
- const targetId = input.targetId ?? defaultTargetId(projectId, workspaceId);
1307
- const stateRoot = projectStateRootForConfig(config, input.stateRoot) ??
1308
- defaultPlexusStateRoot(projectRoot);
1309
- const statePath = projectStatePathForConfig({
1310
- projectRoot,
1311
- config,
1312
- workspaceId,
1313
- stateRoot,
1314
- });
1315
- return {
1316
- projectRoot,
1317
- config,
1318
- stateRoot,
1319
- statePath,
1320
- projectId,
1321
- workspaceId,
1322
- targetId,
1323
- };
1324
- }
1325
- function hostOpenResultForRemoteOpen(input, mapping, openResult, context) {
1326
- const { gateway: _remoteProjectGateway, projectId: _remoteProjectId, projectName: _remoteProjectName, workspaceId: _remoteWorkspaceId, targetId: _remoteTargetId, sourcePath: remoteSourcePath, ...remoteState } = openResult.state;
1327
- const sourcePath = input.sourcePath ?? remoteSourcePath;
1328
- const state = {
1329
- ...remoteState,
1330
- projectId: context.projectId,
1331
- projectName: context.config.name,
1332
- workspaceId: context.workspaceId,
1333
- targetId: context.targetId,
1334
- ...(sourcePath ? { sourcePath } : {}),
1335
- remoteGateway: {
1336
- remoteNodeId: mapping.remoteNode.id,
1337
- endpoint: remoteGatewayEndpointFromUrl(mapping.remoteNode.gatewayMcpUrl),
1338
- projectId: openResult.state.projectId,
1339
- workspaceId: openResult.state.workspaceId,
1340
- targetId: openResult.state.targetId,
1341
- },
1342
- };
1343
- saveProjectState(context.statePath, state);
1344
- return {
1345
- ...openResult,
1346
- projectRoot: context.projectRoot,
1347
- statePath: context.statePath,
1348
- state,
1349
- };
1350
- }
1351
- export class PlexusProjectLifecycle {
1352
- routeRegistry;
1353
- imageToolCaller;
1354
- homeImageCacheClient;
1355
- pharoLauncherMcpClient;
1356
- defaultStateRoot;
1357
- projectOpen;
1358
- projectClose;
1359
- imageRescue;
1360
- remoteClientFactory;
1361
- gateway;
1362
- constructor(options = {}) {
1363
- this.routeRegistry = options.routeRegistry;
1364
- this.imageToolCaller = options.imageToolCaller;
1365
- this.homeImageCacheClient = options.homeImageCacheClient;
1366
- this.pharoLauncherMcpClient = options.pharoLauncherMcpClient;
1367
- this.defaultStateRoot = options.defaultStateRoot;
1368
- this.projectOpen = options.projectOpen ?? openProject;
1369
- this.projectClose = options.projectClose ?? closeProject;
1370
- this.imageRescue = options.imageRescue ?? rescueImage;
1371
- this.remoteClientFactory = options.remoteClientFactory;
1372
- this.gateway = options.gateway ?? {};
1373
- }
1374
- effectiveStateRoot(stateRoot) {
1375
- return stateRoot ?? this.defaultStateRoot;
1376
- }
1377
- remoteLifecycleMapping(input) {
1378
- const projectRoot = path.resolve(input.projectPath);
1379
- if (path.basename(projectRoot) === plexusProjectConfigFileName) {
1380
- return undefined;
1381
- }
1382
- let config;
1383
- try {
1384
- config = loadProjectConfig(projectRoot);
1385
- }
1386
- catch (error) {
1387
- if (error instanceof Error &&
1388
- (error.message.startsWith("ENOENT:") ||
1389
- error.message.startsWith("ENOTDIR:"))) {
1390
- return undefined;
1391
- }
1392
- throw error;
1393
- }
1394
- return remoteLifecycleMappingForInput(config, projectRoot, input);
1395
- }
1396
- remoteClientFor(remoteNode) {
1397
- return (this.remoteClientFactory?.(remoteNode) ??
1398
- new HttpProjectLifecycleClient({
1399
- url: remoteNode.projectMcpUrl,
1400
- timeoutMs: this.gateway.routeRegistryTimeoutMs,
1401
- fetch: this.gateway.fetch,
1402
- }));
1403
- }
1404
- async registerHostRouteForRemoteOpen(input, mapping, openResult) {
1405
- const context = hostRemoteRouteContext({
1406
- ...input,
1407
- stateRoot: this.effectiveStateRoot(input.stateRoot),
1408
- }, mapping);
1409
- const hostOpenResult = hostOpenResultForRemoteOpen(input, mapping, openResult, context);
1410
- await this.ensureGatewayRouteForOpenResult(hostOpenResult);
1411
- return hostOpenResult;
1412
- }
1413
- async unregisterHostRouteForRemote(input, mapping, options = {}) {
1414
- const context = hostRemoteRouteContext({
1415
- ...input,
1416
- stateRoot: this.effectiveStateRoot(input.stateRoot),
1417
- }, mapping);
1418
- const state = loadProjectState(context.statePath);
1419
- const routeRegistry = this.routeRegistry ?? this.routeRegistryForProject(context.config, state);
1420
- await this.unregisterRoute({
1421
- projectId: context.projectId,
1422
- workspaceId: context.workspaceId,
1423
- ...(input.targetId ? { targetId: context.targetId } : {}),
1424
- }, routeRegistry);
1425
- if (state?.gateway?.managedByProject) {
1426
- await closeProjectGateway({
1427
- ...this.gateway,
1428
- state,
1429
- });
1430
- state.updatedAt = (this.gateway.now ?? (() => new Date()))().toISOString();
1431
- saveProjectState(context.statePath, state);
1432
- }
1433
- if (options.deleteStateFile) {
1434
- fs.rmSync(context.statePath, { force: true });
1435
- }
1436
- }
1437
- async open(input) {
1438
- try {
1439
- const remote = this.remoteLifecycleMapping(input);
1440
- if (remote) {
1441
- const remoteResult = await this.remoteClientFor(remote.remoteNode).callTool("plexus_project_open", remoteLifecycleArguments(input, remote));
1442
- if (remoteResult.ok && remoteResult.data) {
1443
- return result(await this.registerHostRouteForRemoteOpen(input, remote, remoteResult.data));
1444
- }
1445
- return remoteResult;
1446
- }
1447
- const openResult = await this.projectOpen({
1448
- projectRoot: input.projectPath,
1449
- sourcePath: input.sourcePath,
1450
- stateRoot: this.effectiveStateRoot(input.stateRoot),
1451
- workspaceId: input.workspaceId,
1452
- targetId: input.targetId,
1453
- displayMode: input.displayMode,
1454
- preparedImageCacheApproval: {
1455
- approved: true,
1456
- runnerId: "plexus-project-open",
1457
- },
1458
- homeImageCacheApproval: {
1459
- approved: true,
1460
- runnerId: "plexus-project-open",
1461
- },
1462
- });
1463
- await this.ensureGatewayRouteForOpenResult(openResult);
1464
- return result(openResult);
1465
- }
1466
- catch (error) {
1467
- if (error instanceof ProjectOpenError &&
1468
- stateHasRunningRoutableImage(error.result.state)) {
1469
- try {
1470
- await this.ensureGatewayRouteForOpenResult(error.result);
1471
- }
1472
- catch {
1473
- // Preserve the project-open failure; diagnostics already carry the
1474
- // image startup failures that made this repair path partial.
1475
- }
1476
- }
1477
- return failure(error);
1478
- }
1479
- }
1480
- async ensureGatewayRouteForOpenResult(openResult) {
1481
- let routeRegistry = this.routeRegistry;
1482
- let startedProjectGateway = false;
1483
- if (!routeRegistry) {
1484
- const config = loadProjectConfig(openResult.projectRoot);
1485
- const discoveredPharoTools = await this.discoverGatewayPharoTools(openResult.state);
1486
- const gatewayResult = await ensureProjectGateway({
1487
- ...this.gateway,
1488
- ...(discoveredPharoTools !== undefined
1489
- ? { pharoTools: discoveredPharoTools }
1490
- : {}),
1491
- projectRoot: openResult.projectRoot,
1492
- config,
1493
- state: openResult.state,
1494
- });
1495
- startedProjectGateway = gatewayResult.started;
1496
- saveProjectState(openResult.statePath, openResult.state);
1497
- routeRegistry = this.routeRegistryFromControlUrl(gatewayResult.routeControlUrl);
1498
- }
1499
- try {
1500
- await this.registerRoute({
1501
- projectRoot: openResult.projectRoot,
1502
- statePath: openResult.statePath,
1503
- state: openResult.state,
1504
- }, routeRegistry);
1505
- }
1506
- catch (error) {
1507
- if (startedProjectGateway) {
1508
- await closeProjectGateway({
1509
- ...this.gateway,
1510
- state: openResult.state,
1511
- });
1512
- saveProjectState(openResult.statePath, openResult.state);
1513
- }
1514
- throw error;
1515
- }
1516
- }
1517
- async discoverGatewayPharoTools(state) {
1518
- if (state.remoteGateway) {
1519
- return undefined;
1520
- }
1521
- if (gatewayHasExplicitPharoTools(this.gateway)) {
1522
- return undefined;
1523
- }
1524
- return discoverPharoMcpToolsFromRunningImages({
1525
- state,
1526
- fetchFn: this.gateway.fetch ?? fetch,
1527
- });
1528
- }
1529
- async homeImageCacheStatus(input) {
1530
- try {
1531
- const projectRoot = path.resolve(input.projectPath);
1532
- const config = loadProjectConfig(projectRoot);
1533
- const homePath = resolvePlexusHomePath({ config });
1534
- const cacheRoot = homeImageCacheRootPath(homePath);
1535
- const entries = input.key
1536
- ? [
1537
- cacheEntryStatusFromReadResult(readHomeImageCacheManifest(homeImageCacheManifestPath(cacheRoot, input.key))),
1538
- ]
1539
- : listHomeImageCacheManifests(cacheRoot).map(cacheEntryStatusFromReadResult);
1540
- return result({
1541
- projectRoot,
1542
- homePath,
1543
- cacheRoot,
1544
- entries,
1545
- });
1546
- }
1547
- catch (error) {
1548
- return failure(error);
1549
- }
1550
- }
1551
- async flushHomeImageCache(input) {
1552
- try {
1553
- if (input.confirm !== true) {
1554
- throw new ProjectLifecycleInputError("confirm: true is required");
1555
- }
1556
- const projectRoot = path.resolve(input.projectPath);
1557
- const config = loadProjectConfig(projectRoot);
1558
- const plan = planHomeImageCacheFlush({
1559
- config,
1560
- key: input.key,
1561
- });
1562
- const homeProfile = homeImageCacheProfile(plan.homePath);
1563
- const manifests = plan.entries
1564
- .map((entry) => readHomeImageCacheManifest(entry.manifestPath))
1565
- .filter((readResult) => readResult.status === "ok")
1566
- .map((readResult) => readResult.manifest);
1567
- let client = this.homeImageCacheClient;
1568
- let ownsClient = false;
1569
- const deletedImages = [];
1570
- try {
1571
- if (manifests.length > 0 && !client) {
1572
- client = await createStdioPharoLauncherMcpClient(undefined, {
1573
- profileEnvironment: profileEnvironmentFromPaths(homeProfile),
1574
- });
1575
- ownsClient = true;
1576
- }
1577
- for (const manifest of manifests) {
1578
- const deleteResult = await client.callTool("pharo_launcher_image_delete", {
1579
- imageName: manifest.cacheImageName,
1580
- force: true,
1581
- confirm: true,
1582
- });
1583
- assertLauncherOk(deleteResult, "pharo_launcher_image_delete");
1584
- deletedImages.push(manifest.cacheImageName);
1585
- }
1586
- }
1587
- finally {
1588
- if (ownsClient) {
1589
- await client?.close?.();
1590
- }
1591
- }
1592
- flushHomeImageCache(plan);
1593
- return result({
1594
- projectRoot,
1595
- homePath: plan.homePath,
1596
- cacheRoot: plan.cacheRoot,
1597
- entries: listHomeImageCacheManifests(plan.cacheRoot).map(cacheEntryStatusFromReadResult),
1598
- deletedImages,
1599
- flushedEntries: plan.entries,
1600
- });
1601
- }
1602
- catch (error) {
1603
- return failure(error);
1604
- }
1605
- }
1606
- routeRegistryForCloseResult(config, closeResult) {
1607
- return (this.routeRegistry ??
1608
- (config && closeResult.state
1609
- ? this.routeRegistryForProject(config, closeResult.state)
1610
- : undefined));
1611
- }
1612
- async unregisterClosedProjectRoute(input, projectRoot, config, closeResult, routeRegistry) {
1613
- if (closeResult.state) {
1614
- await this.unregisterRoute({ targetId: closeResult.state.targetId }, routeRegistry);
1615
- return;
1616
- }
1617
- const workspaceId = input.workspaceId
1618
- ? sanitizeRuntimeId(input.workspaceId)
1619
- : defaultWorkspaceId(projectRoot);
1620
- await this.unregisterRoute({
1621
- projectId: config ? projectConfigId(config) : undefined,
1622
- workspaceId,
1623
- }, routeRegistry);
1624
- }
1625
- async closeManagedProjectGateway(closeResult) {
1626
- if (!closeResult.state?.gateway?.managedByProject) {
1627
- return;
1628
- }
1629
- await closeProjectGateway({
1630
- ...this.gateway,
1631
- state: closeResult.state,
1632
- });
1633
- closeResult.state.updatedAt = (this.gateway.now ?? (() => new Date()))().toISOString();
1634
- saveProjectState(closeResult.statePath, closeResult.state);
1635
- }
1636
- async unregisterClosedProjectRouteAndGateway(input, projectRoot, config, closeResult, routeRegistry) {
1637
- let unregisterError;
1638
- try {
1639
- await this.unregisterClosedProjectRoute(input, projectRoot, config, closeResult, routeRegistry);
1640
- }
1641
- catch (error) {
1642
- unregisterError = error;
1643
- }
1644
- finally {
1645
- await this.closeManagedProjectGateway(closeResult);
1646
- }
1647
- if (unregisterError) {
1648
- throw unregisterError;
1649
- }
1650
- }
1651
- async close(input) {
1652
- try {
1653
- const remote = this.remoteLifecycleMapping(input);
1654
- if (remote) {
1655
- const remoteResult = await this.remoteClientFor(remote.remoteNode).callTool("plexus_project_close", remoteLifecycleArguments(input, remote));
1656
- if (remoteResult.ok) {
1657
- await this.unregisterHostRouteForRemote(input, remote);
1658
- }
1659
- return remoteResult;
1660
- }
1661
- const closeResult = await this.projectClose({
1662
- projectRoot: input.projectPath,
1663
- stateRoot: this.effectiveStateRoot(input.stateRoot),
1664
- workspaceId: input.workspaceId,
1665
- ...(input.repositoryWorkspaceCleanupPolicy
1666
- ? {
1667
- repositoryWorkspaceCleanupPolicy: input.repositoryWorkspaceCleanupPolicy,
1668
- }
1669
- : {}),
1670
- ...(input.repositoryWorkspaceArchiveRoot
1671
- ? { repositoryWorkspaceArchiveRoot: input.repositoryWorkspaceArchiveRoot }
1672
- : {}),
1673
- });
1674
- const projectRoot = path.resolve(input.projectPath);
1675
- const config = !this.routeRegistry || !closeResult.state
1676
- ? loadProjectConfig(projectRoot)
1677
- : undefined;
1678
- await this.unregisterClosedProjectRouteAndGateway(input, projectRoot, config, closeResult, this.routeRegistryForCloseResult(config, closeResult));
1679
- return result(closeResult);
1680
- }
1681
- catch (error) {
1682
- return failure(error);
1683
- }
1684
- }
1685
- async cleanupRouteResource(config, state, routeResource, confirm) {
1686
- if (!(confirm === true && routeResource && state)) {
1687
- return undefined;
1688
- }
1689
- const routeRegistry = this.routeRegistryForProject(config, state);
1690
- if (!routeRegistry) {
1691
- routeResource.status = "skipped";
1692
- routeResource.reason =
1693
- "No route registry is configured for this project scope.";
1694
- return undefined;
1695
- }
1696
- try {
1697
- await this.unregisterRoute({ targetId: state.targetId }, routeRegistry);
1698
- routeResource.status = "cleaned";
1699
- return undefined;
1700
- }
1701
- catch (error) {
1702
- const skipReason = idempotentRouteCleanupReason(error);
1703
- if (skipReason) {
1704
- routeResource.status = "skipped";
1705
- routeResource.reason = skipReason;
1706
- return undefined;
1707
- }
1708
- const message = errorMessage(error);
1709
- routeResource.status = "failed";
1710
- routeResource.reason = message;
1711
- return {
1712
- kind: "route",
1713
- id: state.targetId,
1714
- message,
1715
- };
1716
- }
1717
- }
1718
- async cleanup(input) {
1719
- try {
1720
- const remote = this.remoteLifecycleMapping(input);
1721
- if (remote) {
1722
- const remoteResult = await this.remoteClientFor(remote.remoteNode).callTool("plexus_project_cleanup", remoteLifecycleArguments(input, remote));
1723
- if (remoteResult.ok && input.confirm === true) {
1724
- await this.unregisterHostRouteForRemote(input, remote, {
1725
- deleteStateFile: input.deleteStateFile === true,
1726
- });
1727
- }
1728
- return remoteResult;
1729
- }
1730
- const projectRoot = path.resolve(input.projectPath);
1731
- const config = loadProjectConfig(projectRoot);
1732
- const workspaceId = input.workspaceId
1733
- ? sanitizeRuntimeId(input.workspaceId)
1734
- : defaultWorkspaceId(projectRoot);
1735
- const stateRoot = projectStateRootForConfig(config, this.effectiveStateRoot(input.stateRoot)) ??
1736
- defaultPlexusStateRoot(projectRoot);
1737
- const statePath = projectStatePathForConfig({
1738
- projectRoot,
1739
- config,
1740
- workspaceId,
1741
- stateRoot,
1742
- });
1743
- const state = loadProjectState(statePath);
1744
- const routeResource = state ? routeCleanupResource(state) : undefined;
1745
- const routeFailure = await this.cleanupRouteResource(config, state, routeResource, input.confirm);
1746
- const cleanupResult = await cleanupProjectOwnedResources({
1747
- projectRoot,
1748
- stateRoot,
1749
- workspaceId,
1750
- confirm: input.confirm,
1751
- deleteStateFile: input.deleteStateFile,
1752
- deleteLauncherImages: input.deleteLauncherImages,
1753
- pharoLauncherMcpClient: this.pharoLauncherMcpClient,
1754
- repositoryWorkspaceCleanupPolicy: input.repositoryWorkspaceCleanupPolicy,
1755
- repositoryWorkspaceArchiveRoot: input.repositoryWorkspaceArchiveRoot,
1756
- gateway: this.gateway,
1757
- });
1758
- if (routeResource) {
1759
- cleanupResult.resources.push(routeResource);
1760
- }
1761
- if (routeFailure) {
1762
- cleanupResult.failures.push(routeFailure);
1763
- cleanupResult.ok = false;
1764
- }
1765
- if (!cleanupResult.ok) {
1766
- return {
1767
- ok: false,
1768
- data: cleanupResult,
1769
- error: "One or more PLexus-owned resources failed to clean",
1770
- };
1771
- }
1772
- return result(cleanupResult);
1773
- }
1774
- catch (error) {
1775
- return failure(error);
1776
- }
1777
- }
1778
- async status(input) {
1779
- try {
1780
- if (input.projectPath) {
1781
- const remote = this.remoteLifecycleMapping({
1782
- ...input,
1783
- projectPath: input.projectPath,
1784
- });
1785
- if (remote) {
1786
- return this.remoteClientFor(remote.remoteNode).callTool("plexus_project_status", remoteLifecycleArguments({
1787
- ...input,
1788
- projectPath: input.projectPath,
1789
- }, remote));
1790
- }
1791
- return result(await this.statusFromProjectPath({
1792
- ...input,
1793
- projectPath: input.projectPath,
1794
- }));
1795
- }
1796
- if (!this.routeRegistry?.getRouteStatus) {
1797
- throw new ProjectLifecycleInputError("projectPath is required when no gateway route registry is configured");
1798
- }
1799
- const routeStatus = unwrapToolLikeResult(await this.routeRegistry.getRouteStatus({
1800
- ...lifecycleReferenceFromInput(input),
1801
- refreshHealth: input.refreshHealth,
1802
- }));
1803
- const routes = Array.isArray(routeStatus) ? routeStatus : [routeStatus];
1804
- const statuses = routes.map((route) => lifecycleStatusFromRoute(route, input.includeDiagnostics));
1805
- return result(Array.isArray(routeStatus) ? statuses : statuses[0]);
1806
- }
1807
- catch (error) {
1808
- return failure(error);
1809
- }
1810
- }
1811
- async rescueImage(input) {
1812
- try {
1813
- const imageToolCaller = this.imageToolCaller;
1814
- const options = {
1815
- ...input,
1816
- projectRoot: input.projectPath ?? "",
1817
- stateRoot: this.effectiveStateRoot(input.stateRoot),
1818
- imageMcpClient: imageToolCaller
1819
- ? {
1820
- callTool: async (image, toolName, argumentsValue) => imageToolCaller.callImageTool(lifecycleReferenceFromInput(input), image.id, toolName, argumentsValue),
1821
- }
1822
- : undefined,
1823
- };
1824
- if (!options.projectRoot) {
1825
- throw new ProjectLifecycleInputError("projectPath is required for image rescue");
1826
- }
1827
- const rescueResult = await this.imageRescue(options);
1828
- if (rescueResult.state) {
1829
- const config = loadProjectConfig(rescueResult.projectRoot);
1830
- await this.registerRoute({
1831
- projectRoot: rescueResult.projectRoot,
1832
- statePath: rescueResult.statePath,
1833
- state: rescueResult.state,
1834
- }, this.routeRegistryForProject(config, rescueResult.state));
1835
- }
1836
- return result(rescueResult);
1837
- }
1838
- catch (error) {
1839
- return failure(error);
1840
- }
1841
- }
1842
- async handleTool(name, inputValue) {
1843
- try {
1844
- const input = objectInput(inputValue);
1845
- switch (name) {
1846
- case "plexus_project_open":
1847
- return this.open({
1848
- projectPath: requireString(input, "projectPath"),
1849
- sourcePath: optionalString(input, "sourcePath"),
1850
- stateRoot: optionalString(input, "stateRoot"),
1851
- workspaceId: optionalString(input, "workspaceId"),
1852
- targetId: optionalString(input, "targetId"),
1853
- displayMode: optionalDisplayMode(input, "displayMode"),
1854
- });
1855
- case "plexus_project_close":
1856
- return this.close({
1857
- projectPath: requireString(input, "projectPath"),
1858
- stateRoot: optionalString(input, "stateRoot"),
1859
- workspaceId: optionalString(input, "workspaceId"),
1860
- repositoryWorkspaceCleanupPolicy: optionalRepositoryWorkspaceCleanupPolicy(input),
1861
- repositoryWorkspaceArchiveRoot: optionalString(input, "repositoryWorkspaceArchiveRoot"),
1862
- });
1863
- case "plexus_project_cleanup":
1864
- return this.cleanup({
1865
- projectPath: requireString(input, "projectPath"),
1866
- stateRoot: optionalString(input, "stateRoot"),
1867
- workspaceId: optionalString(input, "workspaceId"),
1868
- confirm: optionalBooleanValue(input, "confirm"),
1869
- deleteStateFile: optionalBooleanValue(input, "deleteStateFile"),
1870
- deleteLauncherImages: optionalBooleanValue(input, "deleteLauncherImages"),
1871
- repositoryWorkspaceCleanupPolicy: optionalRepositoryWorkspaceCleanupPolicy(input),
1872
- repositoryWorkspaceArchiveRoot: optionalString(input, "repositoryWorkspaceArchiveRoot"),
1873
- });
1874
- case "plexus_project_status":
1875
- return this.status({
1876
- projectPath: optionalString(input, "projectPath"),
1877
- sourcePath: optionalString(input, "sourcePath"),
1878
- projectId: optionalString(input, "projectId"),
1879
- workspaceId: optionalString(input, "workspaceId"),
1880
- targetId: optionalString(input, "targetId"),
1881
- stateRoot: optionalString(input, "stateRoot"),
1882
- refreshHealth: optionalBoolean(input, "refreshHealth"),
1883
- includeDiagnostics: optionalBoolean(input, "includeDiagnostics"),
1884
- });
1885
- case "plexus_home_image_cache_status":
1886
- return this.homeImageCacheStatus({
1887
- projectPath: requireString(input, "projectPath"),
1888
- key: optionalString(input, "key"),
1889
- });
1890
- case "plexus_home_image_cache_flush":
1891
- return this.flushHomeImageCache({
1892
- projectPath: requireString(input, "projectPath"),
1893
- key: optionalString(input, "key"),
1894
- confirm: optionalBooleanValue(input, "confirm"),
1895
- });
1896
- case "plexus_rescue_image":
1897
- return this.rescueImage({
1898
- projectPath: requireString(input, "projectPath"),
1899
- projectId: optionalString(input, "projectId"),
1900
- workspaceId: optionalString(input, "workspaceId"),
1901
- targetId: optionalString(input, "targetId"),
1902
- stateRoot: optionalString(input, "stateRoot"),
1903
- operation: requireRescueOperation(input),
1904
- sourceImageId: requireString(input, "sourceImageId"),
1905
- targetImageId: optionalString(input, "targetImageId"),
1906
- targetImageName: optionalString(input, "targetImageName"),
1907
- targetTemplateName: optionalString(input, "targetTemplateName"),
1908
- targetTemplateCategory: optionalString(input, "targetTemplateCategory"),
1909
- targetMcpPort: optionalNumber(input, "targetMcpPort"),
1910
- sourceHistoryDirectoryPath: optionalString(input, "sourceHistoryDirectoryPath"),
1911
- historyFilePath: optionalString(input, "historyFilePath"),
1912
- selection: optionalEntrySelection(input, "selection"),
1913
- exclude: optionalEntrySelection(input, "exclude"),
1914
- codeChangesOnly: optionalBooleanValue(input, "codeChangesOnly"),
1915
- includeEntryCounts: optionalBooleanValue(input, "includeEntryCounts"),
1916
- loadRepositories: optionalBooleanValue(input, "loadRepositories"),
1917
- repositoryActions: optionalRepositoryActions(input, "repositoryActions"),
1918
- confirm: optionalBooleanValue(input, "confirm"),
1919
- });
1920
- default:
1921
- return {
1922
- ok: false,
1923
- error: `Unknown tool: ${name}`,
1924
- };
1925
- }
1926
- }
1927
- catch (error) {
1928
- return failure(error);
1929
- }
1930
- }
1931
- async statusFromProjectPath(input) {
1932
- const projectRoot = path.resolve(input.projectPath);
1933
- if (path.basename(projectRoot) === plexusProjectConfigFileName) {
1934
- throw new ProjectLifecycleInputError(`projectPath must point to the PLexus project directory, not ${plexusProjectConfigFileName}: ` +
1935
- `${projectRoot}. Pass ${path.dirname(projectRoot)} instead.`);
1936
- }
1937
- const config = loadProjectConfig(projectRoot);
1938
- const runtime = resolveProjectRuntimePolicy(config);
1939
- const workspaceId = input.workspaceId
1940
- ? sanitizeRuntimeId(input.workspaceId)
1941
- : defaultWorkspaceId(projectRoot);
1942
- const requestedStateRoot = this.effectiveStateRoot(input.stateRoot);
1943
- const stateRoot = projectStateRootForConfig(config, requestedStateRoot) ??
1944
- defaultPlexusStateRoot(projectRoot);
1945
- const statePath = projectStatePathForConfig({
1946
- projectRoot,
1947
- config,
1948
- workspaceId,
1949
- stateRoot,
1950
- });
1951
- let state = loadProjectState(statePath);
1952
- const checks = mergePortClaimChecks(this.gateway);
1953
- const observedGateway = projectGatewayStatus(config, state);
1954
- const gatewayReconciliation = input.refreshHealth
1955
- ? await reconcileDeadProjectGatewayState({
1956
- state,
1957
- statePath,
1958
- gateway: observedGateway,
1959
- checks,
1960
- now: this.gateway.now ?? (() => new Date()),
1961
- })
1962
- : undefined;
1963
- if (gatewayReconciliation) {
1964
- state = loadProjectState(statePath);
1965
- }
1966
- const requestedSourcePath = input.sourcePath ?? state?.sourcePath;
1967
- const sourcePath = requestedSourcePath
1968
- ? path.resolve(requestedSourcePath)
1969
- : projectRoot;
1970
- const gateway = gatewayReconciliation
1971
- ? gatewayWithoutRuntimeIdentity(projectGatewayStatus(config, state))
1972
- : projectGatewayStatus(config, state);
1973
- const routeRegistry = gatewayReconciliation
1974
- ? undefined
1975
- : this.routeRegistryForProject(config, state);
1976
- let route;
1977
- let routeError;
1978
- if (state) {
1979
- try {
1980
- route = await this.getRouteStatus({
1981
- targetId: state.targetId,
1982
- refreshHealth: input.refreshHealth,
1983
- }, routeRegistry);
1984
- if (routeRegistry &&
1985
- registeredRouteStatePath(route) &&
1986
- !sameResolvedPath(registeredRouteStatePath(route), statePath)) {
1987
- await this.registerRoute({
1988
- projectRoot,
1989
- statePath,
1990
- state,
1991
- }, routeRegistry);
1992
- route = await this.getRouteStatus({
1993
- targetId: state.targetId,
1994
- refreshHealth: input.refreshHealth,
1995
- }, routeRegistry);
1996
- }
1997
- }
1998
- catch (error) {
1999
- routeError = error;
2000
- }
2001
- }
2002
- const targetId = state?.targetId ??
2003
- input.targetId ??
2004
- defaultTargetId(projectConfigId(config), workspaceId);
2005
- const scope = {
2006
- projectId: state?.projectId ?? projectConfigId(config),
2007
- workspaceId: state?.workspaceId ?? workspaceId,
2008
- targetId,
2009
- };
2010
- const gatewayRepair = gatewayRepairAffordance({
2011
- projectRoot,
2012
- stateRoot,
2013
- workspaceId: scope.workspaceId,
2014
- targetId: scope.targetId,
2015
- });
2016
- const context = buildScopedProjectContext({
2017
- projectRoot,
2018
- sourcePath,
2019
- projectConfig: config,
2020
- workspaceId: scope.workspaceId,
2021
- targetId: scope.targetId,
2022
- stateRoot,
2023
- projectState: state,
2024
- });
2025
- const imageClaimsRoot = imagePortClaimsRootForConfig(projectRoot, config);
2026
- const portClaims = await inspectClaimRoots(configuredClaimRoots(projectRoot, config, state), checks, scope, currentScopeClaimPorts(config, state, gateway));
2027
- const routeTable = routeTableDiagnostics(targetId, route, routeError, statePath, gatewayReconciliation);
2028
- const conflictingListeners = await conflictingListenerDiagnostics(state, gateway, portClaims, checks);
2029
- const diagnostics = {
2030
- toolRuntime: plexusRuntimeIdentity(),
2031
- runtime: runtimeDiagnostics(state, gateway, portClaims, conflictingListeners, routeTable, gatewayReconciliation),
2032
- project: projectDiagnostics(config, state),
2033
- scope: {
2034
- projectRoot,
2035
- sourcePath,
2036
- stateRoot,
2037
- statePath,
2038
- projectId: scope.projectId,
2039
- workspaceId: scope.workspaceId,
2040
- targetId: scope.targetId,
2041
- },
2042
- gateway: gatewayDiagnostic(gateway, gatewayReconciliation, gatewayRepair),
2043
- runtimePolicy: runtime,
2044
- remoteTopology: remoteTopologyDiagnostics(config, runtime),
2045
- imagePortPolicy: imagePortPolicyDiagnostics(runtime, stateRoot, imageClaimsRoot),
2046
- launcherProfile: describePharoLauncherMcpProfile({
2047
- projectRoot,
2048
- config,
2049
- workspaceId: scope.workspaceId,
2050
- targetId: scope.targetId,
2051
- stateRoot,
2052
- env: this.gateway.env,
2053
- }),
2054
- agentAccess: agentAccessDiagnostics(gateway, gatewayReconciliation),
2055
- repositoryWorkspaces: repositoryWorkspaceDiagnostics(projectRoot, config, state, scope),
2056
- dependencyRepositoryDetaches: dependencyRepositoryDetachDiagnostics(state),
2057
- imageRecovery: imageRecoveryDiagnostics({
2058
- projectRoot,
2059
- stateRoot,
2060
- workspaceId: scope.workspaceId,
2061
- state,
2062
- }),
2063
- imageMcpPorts: imageMcpPorts(state),
2064
- imagePortCoordination: imagePortCoordinationDiagnostics(projectRoot, stateRoot, config),
2065
- portClaims,
2066
- conflictingListeners,
2067
- staleClaims: portClaims.stale,
2068
- routeTable,
2069
- };
2070
- const safeStatus = {
2071
- projectId: scope.projectId,
2072
- workspaceId: scope.workspaceId,
2073
- targetId: scope.targetId,
2074
- context,
2075
- };
2076
- if (!input.includeDiagnostics) {
2077
- return safeStatus;
2078
- }
2079
- return {
2080
- ...safeStatus,
2081
- projectRoot,
2082
- stateRoot,
2083
- statePath,
2084
- state,
2085
- gateway,
2086
- ...(route ? { route } : {}),
2087
- diagnostics,
2088
- };
2089
- }
2090
- async getRouteStatus(input, routeRegistry = this.routeRegistry) {
2091
- if (!routeRegistry?.getRouteStatus) {
2092
- return undefined;
2093
- }
2094
- return unwrapToolLikeResult(await routeRegistry.getRouteStatus(input));
2095
- }
2096
- async registerRoute(input, routeRegistry = this.routeRegistry) {
2097
- if (!routeRegistry) {
2098
- return;
2099
- }
2100
- unwrapToolLikeResult(await routeRegistry.registerProjectRoute(input));
2101
- }
2102
- async unregisterRoute(input, routeRegistry = this.routeRegistry) {
2103
- if (!routeRegistry) {
2104
- return;
2105
- }
2106
- unwrapToolLikeResult(await routeRegistry.unregisterProjectRoute(input));
2107
- }
2108
- routeRegistryFromControlUrl(url) {
2109
- return new HttpGatewayRouteRegistry({
2110
- url,
2111
- timeoutMs: this.gateway.routeRegistryTimeoutMs,
2112
- fetch: this.gateway.fetch,
2113
- });
2114
- }
2115
- routeRegistryForProject(config, state) {
2116
- if (this.routeRegistry) {
2117
- return this.routeRegistry;
2118
- }
2119
- const gateway = state?.gateway ?? projectGatewayStatus(config, state);
2120
- return gateway.controlEndpoint
2121
- ? this.routeRegistryFromControlUrl(gateway.controlEndpoint)
2122
- : undefined;
2123
- }
2124
- }
2125
- export function createProjectLifecycleFromEnvironment(env = process.env) {
2126
- const routeControlUrl = env.PLEXUS_GATEWAY_CONTROL_MCP_URL;
2127
- const routeControlPath = env.PLEXUS_GATEWAY_CONTROL_MCP_PATH;
2128
- const routeRegistry = routeControlUrl ||
2129
- routeControlPath ||
2130
- env.PLEXUS_GATEWAY_HOST ||
2131
- env.PLEXUS_GATEWAY_PORT
2132
- ? new HttpGatewayRouteRegistry({
2133
- url: routeControlUrl,
2134
- host: env.PLEXUS_GATEWAY_HOST,
2135
- port: env.PLEXUS_GATEWAY_PORT
2136
- ? Number(env.PLEXUS_GATEWAY_PORT)
2137
- : undefined,
2138
- path: routeControlPath,
2139
- })
2140
- : undefined;
2141
- return new PlexusProjectLifecycle({
2142
- routeRegistry,
2143
- defaultStateRoot: env.PLEXUS_STATE_ROOT,
2144
- gateway: { env },
2145
- });
2146
- }
2147
- //# sourceMappingURL=projectLifecycle.js.map