@evref-bl/plexus 0.0.0-stage → 0.1.0-alpha.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 (242) 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 +298 -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 +233 -0
  15. package/dist/config/projectConfig.d.ts.map +1 -0
  16. package/dist/config/projectConfig.js +1181 -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/config.d.ts +29 -0
  23. package/dist/config.d.ts.map +1 -0
  24. package/dist/config.js +111 -0
  25. package/dist/config.js.map +1 -0
  26. package/dist/gateway/projectGateway.d.ts +80 -0
  27. package/dist/gateway/projectGateway.d.ts.map +1 -0
  28. package/dist/gateway/projectGateway.js +435 -0
  29. package/dist/gateway/projectGateway.js.map +1 -0
  30. package/dist/gateway/projectImageMcpEndpoint.d.ts +24 -0
  31. package/dist/gateway/projectImageMcpEndpoint.d.ts.map +1 -0
  32. package/dist/gateway/projectImageMcpEndpoint.js +79 -0
  33. package/dist/gateway/projectImageMcpEndpoint.js.map +1 -0
  34. package/dist/homeImageCache.d.ts +264 -0
  35. package/dist/homeImageCache.d.ts.map +1 -0
  36. package/dist/homeImageCache.js +930 -0
  37. package/dist/homeImageCache.js.map +1 -0
  38. package/dist/imagePortClaims.d.ts +41 -0
  39. package/dist/imagePortClaims.d.ts.map +1 -0
  40. package/dist/imagePortClaims.js +337 -0
  41. package/dist/imagePortClaims.js.map +1 -0
  42. package/dist/imageRescue.d.ts +155 -0
  43. package/dist/imageRescue.d.ts.map +1 -0
  44. package/dist/imageRescue.js +847 -0
  45. package/dist/imageRescue.js.map +1 -0
  46. package/dist/images/homeImageCache.d.ts +264 -0
  47. package/dist/images/homeImageCache.d.ts.map +1 -0
  48. package/dist/images/homeImageCache.js +930 -0
  49. package/dist/images/homeImageCache.js.map +1 -0
  50. package/dist/images/imageRescue.d.ts +155 -0
  51. package/dist/images/imageRescue.d.ts.map +1 -0
  52. package/dist/images/imageRescue.js +847 -0
  53. package/dist/images/imageRescue.js.map +1 -0
  54. package/dist/images/preparedImageCache.d.ts +90 -0
  55. package/dist/images/preparedImageCache.d.ts.map +1 -0
  56. package/dist/images/preparedImageCache.js +237 -0
  57. package/dist/images/preparedImageCache.js.map +1 -0
  58. package/dist/images/scopedTemplateCatalog.d.ts +32 -0
  59. package/dist/images/scopedTemplateCatalog.d.ts.map +1 -0
  60. package/dist/images/scopedTemplateCatalog.js +316 -0
  61. package/dist/images/scopedTemplateCatalog.js.map +1 -0
  62. package/dist/index.d.ts +23 -0
  63. package/dist/index.d.ts.map +1 -0
  64. package/dist/index.js +23 -0
  65. package/dist/index.js.map +1 -0
  66. package/dist/launcher/pharoLauncherMcpClient.d.ts +17 -0
  67. package/dist/launcher/pharoLauncherMcpClient.d.ts.map +1 -0
  68. package/dist/launcher/pharoLauncherMcpClient.js +78 -0
  69. package/dist/launcher/pharoLauncherMcpClient.js.map +1 -0
  70. package/dist/launcher/pharoLauncherProfile.d.ts +31 -0
  71. package/dist/launcher/pharoLauncherProfile.d.ts.map +1 -0
  72. package/dist/launcher/pharoLauncherProfile.js +122 -0
  73. package/dist/launcher/pharoLauncherProfile.js.map +1 -0
  74. package/dist/launcher/scopedPharoLauncherServer.d.ts +247 -0
  75. package/dist/launcher/scopedPharoLauncherServer.d.ts.map +1 -0
  76. package/dist/launcher/scopedPharoLauncherServer.js +1112 -0
  77. package/dist/launcher/scopedPharoLauncherServer.js.map +1 -0
  78. package/dist/lifecycle/projectCleanup.d.ts +59 -0
  79. package/dist/lifecycle/projectCleanup.d.ts.map +1 -0
  80. package/dist/lifecycle/projectCleanup.js +483 -0
  81. package/dist/lifecycle/projectCleanup.js.map +1 -0
  82. package/dist/lifecycle/projectClose.d.ts +35 -0
  83. package/dist/lifecycle/projectClose.d.ts.map +1 -0
  84. package/dist/lifecycle/projectClose.js +273 -0
  85. package/dist/lifecycle/projectClose.js.map +1 -0
  86. package/dist/lifecycle/projectLifecycle.d.ts +429 -0
  87. package/dist/lifecycle/projectLifecycle.d.ts.map +1 -0
  88. package/dist/lifecycle/projectLifecycle.js +2150 -0
  89. package/dist/lifecycle/projectLifecycle.js.map +1 -0
  90. package/dist/lifecycle/projectOpen.d.ts +68 -0
  91. package/dist/lifecycle/projectOpen.d.ts.map +1 -0
  92. package/dist/lifecycle/projectOpen.js +1472 -0
  93. package/dist/lifecycle/projectOpen.js.map +1 -0
  94. package/dist/mcp/pharoMcpHealth.d.ts +26 -0
  95. package/dist/mcp/pharoMcpHealth.d.ts.map +1 -0
  96. package/dist/mcp/pharoMcpHealth.js +97 -0
  97. package/dist/mcp/pharoMcpHealth.js.map +1 -0
  98. package/dist/mcp/server.d.ts +86 -0
  99. package/dist/mcp/server.d.ts.map +1 -0
  100. package/dist/mcp/server.js +357 -0
  101. package/dist/mcp/server.js.map +1 -0
  102. package/dist/pathStyle.d.ts +11 -0
  103. package/dist/pathStyle.d.ts.map +1 -0
  104. package/dist/pathStyle.js +61 -0
  105. package/dist/pathStyle.js.map +1 -0
  106. package/dist/pharoLauncherMcpClient.d.ts +17 -0
  107. package/dist/pharoLauncherMcpClient.d.ts.map +1 -0
  108. package/dist/pharoLauncherMcpClient.js +78 -0
  109. package/dist/pharoLauncherMcpClient.js.map +1 -0
  110. package/dist/pharoLauncherProfile.d.ts +31 -0
  111. package/dist/pharoLauncherProfile.d.ts.map +1 -0
  112. package/dist/pharoLauncherProfile.js +122 -0
  113. package/dist/pharoLauncherProfile.js.map +1 -0
  114. package/dist/pharoMcpHealth.d.ts +26 -0
  115. package/dist/pharoMcpHealth.d.ts.map +1 -0
  116. package/dist/pharoMcpHealth.js +97 -0
  117. package/dist/pharoMcpHealth.js.map +1 -0
  118. package/dist/plexusHome.d.ts +17 -0
  119. package/dist/plexusHome.d.ts.map +1 -0
  120. package/dist/plexusHome.js +30 -0
  121. package/dist/plexusHome.js.map +1 -0
  122. package/dist/portClaims.d.ts +116 -0
  123. package/dist/portClaims.d.ts.map +1 -0
  124. package/dist/portClaims.js +393 -0
  125. package/dist/portClaims.js.map +1 -0
  126. package/dist/ports/imagePortClaims.d.ts +41 -0
  127. package/dist/ports/imagePortClaims.d.ts.map +1 -0
  128. package/dist/ports/imagePortClaims.js +337 -0
  129. package/dist/ports/imagePortClaims.js.map +1 -0
  130. package/dist/ports/portClaims.d.ts +116 -0
  131. package/dist/ports/portClaims.d.ts.map +1 -0
  132. package/dist/ports/portClaims.js +393 -0
  133. package/dist/ports/portClaims.js.map +1 -0
  134. package/dist/preparedImageCache.d.ts +90 -0
  135. package/dist/preparedImageCache.d.ts.map +1 -0
  136. package/dist/preparedImageCache.js +237 -0
  137. package/dist/preparedImageCache.js.map +1 -0
  138. package/dist/projectCleanup.d.ts +59 -0
  139. package/dist/projectCleanup.d.ts.map +1 -0
  140. package/dist/projectCleanup.js +483 -0
  141. package/dist/projectCleanup.js.map +1 -0
  142. package/dist/projectClose.d.ts +35 -0
  143. package/dist/projectClose.d.ts.map +1 -0
  144. package/dist/projectClose.js +273 -0
  145. package/dist/projectClose.js.map +1 -0
  146. package/dist/projectConfig.d.ts +233 -0
  147. package/dist/projectConfig.d.ts.map +1 -0
  148. package/dist/projectConfig.js +1181 -0
  149. package/dist/projectConfig.js.map +1 -0
  150. package/dist/projectGateway.d.ts +80 -0
  151. package/dist/projectGateway.d.ts.map +1 -0
  152. package/dist/projectGateway.js +435 -0
  153. package/dist/projectGateway.js.map +1 -0
  154. package/dist/projectImageMcpEndpoint.d.ts +24 -0
  155. package/dist/projectImageMcpEndpoint.d.ts.map +1 -0
  156. package/dist/projectImageMcpEndpoint.js +79 -0
  157. package/dist/projectImageMcpEndpoint.js.map +1 -0
  158. package/dist/projectLifecycle.d.ts +428 -0
  159. package/dist/projectLifecycle.d.ts.map +1 -0
  160. package/dist/projectLifecycle.js +2147 -0
  161. package/dist/projectLifecycle.js.map +1 -0
  162. package/dist/projectOpen.d.ts +68 -0
  163. package/dist/projectOpen.d.ts.map +1 -0
  164. package/dist/projectOpen.js +1472 -0
  165. package/dist/projectOpen.js.map +1 -0
  166. package/dist/projectRepositoryWorkspace.d.ts +74 -0
  167. package/dist/projectRepositoryWorkspace.d.ts.map +1 -0
  168. package/dist/projectRepositoryWorkspace.js +553 -0
  169. package/dist/projectRepositoryWorkspace.js.map +1 -0
  170. package/dist/projectStartupScript.d.ts +74 -0
  171. package/dist/projectStartupScript.d.ts.map +1 -0
  172. package/dist/projectStartupScript.js +748 -0
  173. package/dist/projectStartupScript.js.map +1 -0
  174. package/dist/projectState.d.ts +315 -0
  175. package/dist/projectState.d.ts.map +1 -0
  176. package/dist/projectState.js +399 -0
  177. package/dist/projectState.js.map +1 -0
  178. package/dist/runtimeIdentity.d.ts +15 -0
  179. package/dist/runtimeIdentity.d.ts.map +1 -0
  180. package/dist/runtimeIdentity.js +25 -0
  181. package/dist/runtimeIdentity.js.map +1 -0
  182. package/dist/scopedPharoLauncherServer.d.ts +247 -0
  183. package/dist/scopedPharoLauncherServer.d.ts.map +1 -0
  184. package/dist/scopedPharoLauncherServer.js +1112 -0
  185. package/dist/scopedPharoLauncherServer.js.map +1 -0
  186. package/dist/scopedProjectContext.d.ts +169 -0
  187. package/dist/scopedProjectContext.d.ts.map +1 -0
  188. package/dist/scopedProjectContext.js +358 -0
  189. package/dist/scopedProjectContext.js.map +1 -0
  190. package/dist/scopedTemplateCatalog.d.ts +32 -0
  191. package/dist/scopedTemplateCatalog.d.ts.map +1 -0
  192. package/dist/scopedTemplateCatalog.js +316 -0
  193. package/dist/scopedTemplateCatalog.js.map +1 -0
  194. package/dist/server.d.ts +86 -0
  195. package/dist/server.d.ts.map +1 -0
  196. package/dist/server.js +357 -0
  197. package/dist/server.js.map +1 -0
  198. package/dist/support/pathStyle.d.ts +11 -0
  199. package/dist/support/pathStyle.d.ts.map +1 -0
  200. package/dist/support/pathStyle.js +61 -0
  201. package/dist/support/pathStyle.js.map +1 -0
  202. package/dist/support/runtimeIdentity.d.ts +15 -0
  203. package/dist/support/runtimeIdentity.d.ts.map +1 -0
  204. package/dist/support/runtimeIdentity.js +40 -0
  205. package/dist/support/runtimeIdentity.js.map +1 -0
  206. package/dist/support/toolResultFormatting.d.ts +8 -0
  207. package/dist/support/toolResultFormatting.d.ts.map +1 -0
  208. package/dist/support/toolResultFormatting.js +81 -0
  209. package/dist/support/toolResultFormatting.js.map +1 -0
  210. package/dist/target.d.ts +19 -0
  211. package/dist/target.d.ts.map +1 -0
  212. package/dist/target.js +2 -0
  213. package/dist/target.js.map +1 -0
  214. package/dist/toolResultFormatting.d.ts +8 -0
  215. package/dist/toolResultFormatting.d.ts.map +1 -0
  216. package/dist/toolResultFormatting.js +81 -0
  217. package/dist/toolResultFormatting.js.map +1 -0
  218. package/dist/workspace/projectRepositoryWorkspace.d.ts +74 -0
  219. package/dist/workspace/projectRepositoryWorkspace.d.ts.map +1 -0
  220. package/dist/workspace/projectRepositoryWorkspace.js +553 -0
  221. package/dist/workspace/projectRepositoryWorkspace.js.map +1 -0
  222. package/dist/workspace/projectStartupScript.d.ts +74 -0
  223. package/dist/workspace/projectStartupScript.d.ts.map +1 -0
  224. package/dist/workspace/projectStartupScript.js +748 -0
  225. package/dist/workspace/projectStartupScript.js.map +1 -0
  226. package/dist/workspace/projectState.d.ts +320 -0
  227. package/dist/workspace/projectState.d.ts.map +1 -0
  228. package/dist/workspace/projectState.js +399 -0
  229. package/dist/workspace/projectState.js.map +1 -0
  230. package/dist/workspace/scopedProjectContext.d.ts +169 -0
  231. package/dist/workspace/scopedProjectContext.d.ts.map +1 -0
  232. package/dist/workspace/scopedProjectContext.js +358 -0
  233. package/dist/workspace/scopedProjectContext.js.map +1 -0
  234. package/dist/workspace/workspaceMcpConfig.d.ts +51 -0
  235. package/dist/workspace/workspaceMcpConfig.d.ts.map +1 -0
  236. package/dist/workspace/workspaceMcpConfig.js +98 -0
  237. package/dist/workspace/workspaceMcpConfig.js.map +1 -0
  238. package/dist/workspaceMcpConfig.d.ts +51 -0
  239. package/dist/workspaceMcpConfig.d.ts.map +1 -0
  240. package/dist/workspaceMcpConfig.js +98 -0
  241. package/dist/workspaceMcpConfig.js.map +1 -0
  242. package/package.json +39 -4
@@ -0,0 +1,1472 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { loadProjectConfig, projectImageDisplayMode, projectConfigId, projectMcpStartupMode, resolveProjectRuntimePolicy, } from "../config/projectConfig.js";
4
+ import { dirnamePathLike, isAbsolutePathLike, joinPathLike, resolvePathLike, } from "../support/pathStyle.js";
5
+ import { defaultImagePortClaimChecks, imagePortClaimsRootForConfig, prepareImagePortClaims, recordImagePortClaimProcess, releaseImagePortClaimIfOwned, releasePreparedImagePortClaims, } from "../ports/imagePortClaims.js";
6
+ import { createStdioPharoLauncherMcpClient, PharoLauncherMcpToolError, } from "../launcher/pharoLauncherMcpClient.js";
7
+ import { copyProjectImageFromPreparedCache, } from "../images/preparedImageCache.js";
8
+ import { materializeProjectImageFromHomeCache, projectImageCanUseHomeImageCache, } from "../images/homeImageCache.js";
9
+ import { pharoLauncherMcpProfileEnvironment } from "../launcher/pharoLauncherProfile.js";
10
+ import { HttpPharoMcpHealthClient, } from "../mcp/pharoMcpHealth.js";
11
+ import { imageMcpEndpointHandoffPath, readImageMcpEndpointHandoff, removeImageMcpEndpointHandoff, } from "../gateway/projectImageMcpEndpoint.js";
12
+ import { collectReservedProjectPortOwners, createProjectState, defaultWorkspaceId, loadProjectState, projectImageRepositoryWorkspaces, projectStatePathForConfig, projectStateRootForConfig, runtimeStatusForImages, sanitizeRuntimeId, saveProjectState, } from "../workspace/projectState.js";
13
+ import { writeProjectImageStartupScript } from "../workspace/projectStartupScript.js";
14
+ import { materializeProjectImageRepositoryWorkspaces } from "../workspace/projectRepositoryWorkspace.js";
15
+ export class ProjectOpenError extends Error {
16
+ result;
17
+ constructor(message, result) {
18
+ super(message);
19
+ this.result = result;
20
+ this.name = "ProjectOpenError";
21
+ }
22
+ }
23
+ function defaultSleep(durationMs) {
24
+ return new Promise((resolve) => setTimeout(resolve, durationMs));
25
+ }
26
+ function errorMessage(error) {
27
+ return error instanceof Error ? error.message : String(error);
28
+ }
29
+ function launcherFailureDetails(error) {
30
+ if (!(error instanceof PharoLauncherMcpToolError)) {
31
+ return {};
32
+ }
33
+ const result = error.result;
34
+ const objectResult = isObject(result) ? result : undefined;
35
+ return {
36
+ launcherToolName: error.toolName,
37
+ launcherResult: result,
38
+ ...(typeof objectResult?.diagnostic === "string"
39
+ ? { diagnostic: objectResult.diagnostic }
40
+ : {}),
41
+ ...(typeof objectResult?.action === "string"
42
+ ? { action: objectResult.action }
43
+ : {}),
44
+ };
45
+ }
46
+ function closeClientQuietly(client) {
47
+ void client.close?.().catch(() => undefined);
48
+ }
49
+ function processDirectlyMatchesImage(process, imageName) {
50
+ return (process.imageName === imageName ||
51
+ path.basename(process.imagePath ?? "", ".image") === imageName ||
52
+ process.commandLine.includes(`${imageName}.image`));
53
+ }
54
+ function launcherResultData(result) {
55
+ return result.ok ? result.data : undefined;
56
+ }
57
+ function assertLauncherOk(result, toolName) {
58
+ if (result && result.ok === false) {
59
+ throw new Error(`${toolName} returned ok: false`);
60
+ }
61
+ }
62
+ class ImageStartupExitedBeforeHealthError extends Error {
63
+ launcherResult;
64
+ process;
65
+ constructor(message, launcherResult, process) {
66
+ super(message);
67
+ this.launcherResult = launcherResult;
68
+ this.process = process;
69
+ this.name = "ImageStartupExitedBeforeHealthError";
70
+ }
71
+ }
72
+ function isObject(value) {
73
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
74
+ }
75
+ function imageMcpEndpointForImage(image) {
76
+ if (image.mcpEndpoint) {
77
+ return image.mcpEndpoint;
78
+ }
79
+ if (image.assignedPort !== undefined) {
80
+ return {
81
+ transport: "http",
82
+ host: "127.0.0.1",
83
+ port: image.assignedPort,
84
+ path: "/",
85
+ };
86
+ }
87
+ return undefined;
88
+ }
89
+ function hostForUrl(host) {
90
+ return host.includes(":") && !host.startsWith("[") ? `[${host}]` : host;
91
+ }
92
+ function imageMcpEndpointUrl(endpoint) {
93
+ return `http://${hostForUrl(endpoint.host)}:${endpoint.port}${endpoint.path}`;
94
+ }
95
+ function jsonRpcErrorText(value) {
96
+ if (isObject(value) && typeof value.message === "string") {
97
+ return value.message;
98
+ }
99
+ try {
100
+ return JSON.stringify(value);
101
+ }
102
+ catch {
103
+ return String(value);
104
+ }
105
+ }
106
+ class HttpProjectOpenImageMcpClient {
107
+ fetchFn;
108
+ timeoutMs;
109
+ constructor(fetchFn = fetch, timeoutMs = 60_000) {
110
+ this.fetchFn = fetchFn;
111
+ this.timeoutMs = timeoutMs;
112
+ }
113
+ async callTool(image, toolName, argumentsValue) {
114
+ const endpoint = imageMcpEndpointForImage(image);
115
+ if (!endpoint) {
116
+ throw new Error(`Image ${image.id} has no routable Pharo MCP endpoint`);
117
+ }
118
+ const controller = new AbortController();
119
+ const timeout = setTimeout(() => controller.abort(), this.timeoutMs);
120
+ try {
121
+ const response = await this.fetchFn(imageMcpEndpointUrl(endpoint), {
122
+ method: "POST",
123
+ headers: {
124
+ accept: "application/json, text/event-stream",
125
+ "content-type": "application/json",
126
+ },
127
+ body: JSON.stringify({
128
+ jsonrpc: "2.0",
129
+ id: `plexus-open-${image.id}-${Date.now()}`,
130
+ method: "tools/call",
131
+ params: {
132
+ name: toolName,
133
+ arguments: argumentsValue,
134
+ },
135
+ }),
136
+ signal: controller.signal,
137
+ });
138
+ if (!response.ok) {
139
+ throw new Error(`MCP tools/call failed with HTTP ${response.status}`);
140
+ }
141
+ const payload = (await response.json());
142
+ if (!isObject(payload)) {
143
+ throw new Error("MCP tools/call response was not a JSON object");
144
+ }
145
+ if ("error" in payload) {
146
+ throw new Error(`MCP error ${jsonRpcErrorText(payload.error)}`);
147
+ }
148
+ if (!("result" in payload)) {
149
+ throw new Error("MCP tools/call response did not include a result");
150
+ }
151
+ return payload.result;
152
+ }
153
+ finally {
154
+ clearTimeout(timeout);
155
+ }
156
+ }
157
+ }
158
+ function optionalStringField(value, key) {
159
+ return typeof value[key] === "string" && value[key].length > 0
160
+ ? value[key]
161
+ : undefined;
162
+ }
163
+ function launcherImageInfo(value) {
164
+ if (!isObject(value)) {
165
+ return undefined;
166
+ }
167
+ const originTemplate = isObject(value.originTemplate)
168
+ ? {
169
+ ...(optionalStringField(value.originTemplate, "name")
170
+ ? { name: optionalStringField(value.originTemplate, "name") }
171
+ : {}),
172
+ ...(optionalStringField(value.originTemplate, "url")
173
+ ? { url: optionalStringField(value.originTemplate, "url") }
174
+ : {}),
175
+ }
176
+ : undefined;
177
+ const pharoVersion = typeof value.pharoVersion === "string" || typeof value.pharoVersion === "number"
178
+ ? value.pharoVersion
179
+ : undefined;
180
+ return {
181
+ imagePath: optionalStringField(value, "imagePath"),
182
+ imageDirectoryPath: optionalStringField(value, "imageDirectoryPath"),
183
+ changesPath: optionalStringField(value, "changesPath"),
184
+ localDirectoryPath: optionalStringField(value, "localDirectoryPath"),
185
+ ombuDirectoryPath: optionalStringField(value, "ombuDirectoryPath"),
186
+ ...(pharoVersion !== undefined ? { pharoVersion } : {}),
187
+ vmId: optionalStringField(value, "vmId"),
188
+ ...(originTemplate ? { originTemplate } : {}),
189
+ };
190
+ }
191
+ function logPathFromLine(line) {
192
+ const separator = line.indexOf(":");
193
+ if (separator < 0) {
194
+ return undefined;
195
+ }
196
+ const key = line.slice(0, separator).trim().toLowerCase();
197
+ if (key !== "stdout" && key !== "stderr" && key !== "log" && key !== "logpath") {
198
+ return undefined;
199
+ }
200
+ const value = line.slice(separator + 1).trim();
201
+ return value.length > 0 ? value : undefined;
202
+ }
203
+ function logPathsFromText(value) {
204
+ return value
205
+ .split(/\r?\n/)
206
+ .map(logPathFromLine)
207
+ .filter((path) => Boolean(path));
208
+ }
209
+ function profileScopedImagePidFromText(value) {
210
+ const match = value.match(/\bDetached\s+profile-scoped\s+Pharo\s+image\s+pid\s+(\d+)\b/i);
211
+ if (!match) {
212
+ return undefined;
213
+ }
214
+ return Number.parseInt(match[1], 10);
215
+ }
216
+ function launcherPidFromValue(value, fieldName) {
217
+ if (typeof value === "number" && Number.isInteger(value) && value > 0) {
218
+ const normalizedFieldName = fieldName?.toLowerCase() ?? "";
219
+ return normalizedFieldName === "pid" || normalizedFieldName === "processid"
220
+ ? value
221
+ : undefined;
222
+ }
223
+ if (typeof value === "string") {
224
+ const normalizedFieldName = fieldName?.toLowerCase() ?? "";
225
+ if (normalizedFieldName === "pid" || normalizedFieldName === "processid") {
226
+ const parsed = Number.parseInt(value, 10);
227
+ return Number.isInteger(parsed) && parsed > 0 ? parsed : undefined;
228
+ }
229
+ return profileScopedImagePidFromText(value);
230
+ }
231
+ if (!isObject(value)) {
232
+ return undefined;
233
+ }
234
+ for (const [key, fieldValue] of Object.entries(value)) {
235
+ const pid = launcherPidFromValue(fieldValue, key);
236
+ if (pid !== undefined) {
237
+ return pid;
238
+ }
239
+ }
240
+ return undefined;
241
+ }
242
+ function launcherProcessFromResult(result, imageName) {
243
+ const pid = launcherPidFromValue(result);
244
+ if (pid === undefined) {
245
+ return undefined;
246
+ }
247
+ return {
248
+ pid,
249
+ imageName,
250
+ commandLine: `pharo_launcher_image_launch ${imageName}`,
251
+ };
252
+ }
253
+ function isPidAlive(pid) {
254
+ try {
255
+ globalThis.process.kill(pid, 0);
256
+ return true;
257
+ }
258
+ catch (error) {
259
+ return isObject(error) && error.code === "ESRCH" ? false : true;
260
+ }
261
+ }
262
+ function collectLauncherLogPaths(value, fieldName) {
263
+ if (typeof value === "string") {
264
+ if (value.length === 0) {
265
+ return [];
266
+ }
267
+ const paths = logPathsFromText(value);
268
+ if (paths.length > 0) {
269
+ return paths;
270
+ }
271
+ const normalizedFieldName = fieldName?.toLowerCase() ?? "";
272
+ return normalizedFieldName.includes("log") ||
273
+ normalizedFieldName.includes("stdout") ||
274
+ normalizedFieldName.includes("stderr")
275
+ ? [value]
276
+ : [];
277
+ }
278
+ if (!isObject(value)) {
279
+ return [];
280
+ }
281
+ const paths = [];
282
+ for (const [key, fieldValue] of Object.entries(value)) {
283
+ paths.push(...collectLauncherLogPaths(fieldValue, key));
284
+ }
285
+ return [...new Set(paths)];
286
+ }
287
+ function startupFailureDetails(error) {
288
+ if (!(error instanceof ImageStartupExitedBeforeHealthError)) {
289
+ return {};
290
+ }
291
+ return {
292
+ launcherToolName: "pharo_launcher_image_launch",
293
+ launcherResult: error.launcherResult,
294
+ process: error.process,
295
+ };
296
+ }
297
+ function profileImagesDirectory(value) {
298
+ if (!isObject(value) || !isObject(value.profile) || !isObject(value.profile.imagesDir)) {
299
+ return undefined;
300
+ }
301
+ return optionalStringField(value.profile.imagesDir, "path");
302
+ }
303
+ async function launcherImagesDirectory(client) {
304
+ const result = await client.callTool("pharo_launcher_config", {});
305
+ assertLauncherOk(result, "pharo_launcher_config");
306
+ return profileImagesDirectory(launcherResultData(result));
307
+ }
308
+ function normalizeImagePath(imagePath, imagesDirectory) {
309
+ if (isAbsolutePathLike(imagePath)) {
310
+ return resolvePathLike(imagePath);
311
+ }
312
+ return imagesDirectory ? joinPathLike(imagesDirectory, imagePath) : imagePath;
313
+ }
314
+ function applyLauncherImageInfo(imageState, info, imagesDirectory) {
315
+ if (!info) {
316
+ return;
317
+ }
318
+ const imagePath = info.imagePath
319
+ ? normalizeImagePath(info.imagePath, imagesDirectory)
320
+ : undefined;
321
+ const imageDirectoryPath = info.imageDirectoryPath ??
322
+ (imagePath ? dirnamePathLike(imagePath) : undefined);
323
+ imageState.imagePath = imagePath ?? imageState.imagePath;
324
+ imageState.imageDirectoryPath =
325
+ imageDirectoryPath ?? imageState.imageDirectoryPath;
326
+ imageState.changesPath =
327
+ info.changesPath ??
328
+ (imagePath ? imagePath.replace(/\.image$/i, ".changes") : imageState.changesPath);
329
+ imageState.localDirectoryPath =
330
+ info.localDirectoryPath ??
331
+ (imageDirectoryPath
332
+ ? joinPathLike(imageDirectoryPath, "pharo-local")
333
+ : imageState.localDirectoryPath);
334
+ imageState.ombuDirectoryPath =
335
+ info.ombuDirectoryPath ??
336
+ (imageDirectoryPath
337
+ ? joinPathLike(imageDirectoryPath, "ombu")
338
+ : imageState.ombuDirectoryPath);
339
+ imageState.vmId = info.vmId ?? imageState.vmId;
340
+ imageState.pharoVersion =
341
+ info.pharoVersion !== undefined
342
+ ? String(info.pharoVersion)
343
+ : imageState.pharoVersion;
344
+ imageState.originTemplate = info.originTemplate ?? imageState.originTemplate;
345
+ }
346
+ function applyLauncherProfileImagePathFallback(imageState, imagesDirectory) {
347
+ if (!imagesDirectory || !repositoryWorkspaceNeedsLauncherPaths(imageState)) {
348
+ return;
349
+ }
350
+ const imageDirectoryPath = joinPathLike(imagesDirectory, imageState.imageName);
351
+ const imagePath = joinPathLike(imageDirectoryPath, `${imageState.imageName}.image`);
352
+ if (!fs.existsSync(imagePath)) {
353
+ return;
354
+ }
355
+ applyLauncherImageInfo(imageState, {
356
+ imagePath,
357
+ imageDirectoryPath,
358
+ changesPath: joinPathLike(imageDirectoryPath, `${imageState.imageName}.changes`),
359
+ localDirectoryPath: joinPathLike(imageDirectoryPath, "pharo-local"),
360
+ ombuDirectoryPath: joinPathLike(imageDirectoryPath, "ombu"),
361
+ });
362
+ }
363
+ function repositoryWorkspaceNeedsLauncherPaths(imageState) {
364
+ return (!imageState.localDirectoryPath &&
365
+ projectImageRepositoryWorkspaces(imageState).some((workspace) => workspace.path.startsWith("image-local://")));
366
+ }
367
+ function appendRepositoryWorkspaceDiagnostic(workspace, message) {
368
+ if (workspace.diagnostics.includes(message)) {
369
+ return;
370
+ }
371
+ workspace.diagnostics = [...workspace.diagnostics, message];
372
+ }
373
+ function repositoryWorkspaceSourcePath(workspace) {
374
+ return workspace.loadSourcePath ?? joinPathLike(workspace.path, workspace.sourceDirectory);
375
+ }
376
+ function inferTonelPackageNames(sourcePath) {
377
+ if (!fs.existsSync(sourcePath)) {
378
+ return [];
379
+ }
380
+ return fs
381
+ .readdirSync(sourcePath, { withFileTypes: true })
382
+ .filter((entry) => entry.isDirectory() &&
383
+ fs.existsSync(joinPathLike(sourcePath, entry.name, "package.st")))
384
+ .map((entry) => entry.name)
385
+ .sort((left, right) => left.localeCompare(right));
386
+ }
387
+ function toolStructuredContent(result) {
388
+ if (!isObject(result) || !isObject(result.structuredContent)) {
389
+ return undefined;
390
+ }
391
+ return result.structuredContent;
392
+ }
393
+ function toolTextContent(result) {
394
+ if (!isObject(result) || !Array.isArray(result.content)) {
395
+ return undefined;
396
+ }
397
+ const item = result.content.find((candidate) => isObject(candidate) &&
398
+ candidate.type === "text" &&
399
+ typeof candidate.text === "string");
400
+ return item?.text;
401
+ }
402
+ function toolErrorMessage(result, toolName) {
403
+ const structuredContent = toolStructuredContent(result);
404
+ if (typeof structuredContent?.summary === "string") {
405
+ return structuredContent.summary;
406
+ }
407
+ const text = toolTextContent(result);
408
+ if (text) {
409
+ return text;
410
+ }
411
+ return `${toolName} returned an error result`;
412
+ }
413
+ function assertToolResultOk(result, toolName) {
414
+ const structuredContent = toolStructuredContent(result);
415
+ if (structuredContent?.status !== "error" &&
416
+ (!isObject(result) || result.isError !== true)) {
417
+ return;
418
+ }
419
+ throw new Error(toolErrorMessage(result, toolName));
420
+ }
421
+ function toolResultData(result) {
422
+ const structuredContent = toolStructuredContent(result);
423
+ if (isObject(structuredContent?.data)) {
424
+ return structuredContent.data;
425
+ }
426
+ if (isObject(result) && isObject(result.data)) {
427
+ return result.data;
428
+ }
429
+ return {};
430
+ }
431
+ function repositoryEntriesFromToolResult(result) {
432
+ const repositories = toolResultData(result).repositories;
433
+ return Array.isArray(repositories)
434
+ ? repositories.filter((entry) => isObject(entry))
435
+ : [];
436
+ }
437
+ async function callImageMcpToolForOpen(options) {
438
+ const result = await options.imageMcpClient.callTool(options.imageState, options.toolName, options.argumentsValue);
439
+ assertToolResultOk(result, options.toolName);
440
+ return result;
441
+ }
442
+ async function callDiscoverableImageMcpToolForOpen(options) {
443
+ return callImageMcpToolForOpen({
444
+ imageMcpClient: options.imageMcpClient,
445
+ imageState: options.imageState,
446
+ toolName: "tool_call",
447
+ argumentsValue: {
448
+ toolName: options.toolName,
449
+ arguments: options.argumentsValue,
450
+ },
451
+ });
452
+ }
453
+ function repositoryEntryName(entry, fallback) {
454
+ return typeof entry?.name === "string" && entry.name.length > 0
455
+ ? entry.name
456
+ : fallback;
457
+ }
458
+ function matchingRepositoryEntry(entries, repositoryPath) {
459
+ return entries.find((entry) => entry.location === repositoryPath) ?? entries[0];
460
+ }
461
+ async function ensureRepositoryWorkspaceRegistered(options) {
462
+ const workspace = options.workspace;
463
+ if (!workspace || workspace.loadState !== "loaded") {
464
+ return;
465
+ }
466
+ const endpoint = imageMcpEndpointForImage(options.imageState);
467
+ if (!endpoint) {
468
+ const message = `Repository workspace registration skipped for image ${options.imageState.id}: image has no routable Pharo MCP endpoint.`;
469
+ workspace.registrationState = "skipped";
470
+ workspace.registrationError = message;
471
+ appendRepositoryWorkspaceDiagnostic(workspace, message);
472
+ if (imageRequiresPharoMcpHealth(options.imageConfig, options.imageState)) {
473
+ workspace.registrationState = "failed";
474
+ throw new Error(message);
475
+ }
476
+ return;
477
+ }
478
+ if (!imageCanRouteToPharoMcp(options.imageConfig, options.imageState)) {
479
+ const message = `Repository workspace registration skipped for image ${options.imageState.id}: Pharo MCP startup is disabled or unsupported.`;
480
+ workspace.registrationState = "skipped";
481
+ workspace.registrationError = message;
482
+ appendRepositoryWorkspaceDiagnostic(workspace, message);
483
+ return;
484
+ }
485
+ workspace.registrationState = "pending";
486
+ delete workspace.registrationError;
487
+ delete workspace.registeredRepositoryName;
488
+ delete workspace.registeredPackageNames;
489
+ const packageNames = inferTonelPackageNames(repositoryWorkspaceSourcePath(workspace));
490
+ const repositoryPath = workspace.path;
491
+ const repositoryId = workspace.repository.id;
492
+ try {
493
+ const findResult = await callDiscoverableImageMcpToolForOpen({
494
+ imageMcpClient: options.imageMcpClient,
495
+ imageState: options.imageState,
496
+ toolName: "repository_search",
497
+ argumentsValue: {
498
+ directoryPaths: [repositoryPath],
499
+ limit: 1000,
500
+ },
501
+ });
502
+ const existingRepository = matchingRepositoryEntry(repositoryEntriesFromToolResult(findResult), repositoryPath);
503
+ const repositoryName = repositoryEntryName(existingRepository, repositoryId);
504
+ const repositoryArguments = {
505
+ location: repositoryPath,
506
+ subdirectory: workspace.sourceDirectory,
507
+ packageNames,
508
+ };
509
+ if (existingRepository) {
510
+ await callDiscoverableImageMcpToolForOpen({
511
+ imageMcpClient: options.imageMcpClient,
512
+ imageState: options.imageState,
513
+ toolName: "repository_update",
514
+ argumentsValue: {
515
+ repositoryName,
516
+ ...repositoryArguments,
517
+ },
518
+ });
519
+ }
520
+ else {
521
+ await callDiscoverableImageMcpToolForOpen({
522
+ imageMcpClient: options.imageMcpClient,
523
+ imageState: options.imageState,
524
+ toolName: "repository_attach",
525
+ argumentsValue: {
526
+ name: repositoryName,
527
+ ...repositoryArguments,
528
+ },
529
+ });
530
+ }
531
+ await callDiscoverableImageMcpToolForOpen({
532
+ imageMcpClient: options.imageMcpClient,
533
+ imageState: options.imageState,
534
+ toolName: "repository_identity_verify",
535
+ argumentsValue: {
536
+ repositoryName,
537
+ ...repositoryArguments,
538
+ },
539
+ });
540
+ workspace.registrationState = "registered";
541
+ workspace.registeredRepositoryName = repositoryName;
542
+ workspace.registeredPackageNames = packageNames;
543
+ }
544
+ catch (error) {
545
+ const message = errorMessage(error);
546
+ workspace.registrationState = "failed";
547
+ workspace.registrationError = message;
548
+ appendRepositoryWorkspaceDiagnostic(workspace, message);
549
+ throw new Error(`Repository workspace registration failed for image ${options.imageState.id}: ${message}`);
550
+ }
551
+ }
552
+ function parseStatusProperties(filePath) {
553
+ return Object.fromEntries(fs
554
+ .readFileSync(filePath, "utf8")
555
+ .split(/\r\n|\n|\r/)
556
+ .map((line) => {
557
+ if (!line || line.startsWith("#")) {
558
+ return undefined;
559
+ }
560
+ const separator = line.indexOf("=");
561
+ if (separator <= 0) {
562
+ return undefined;
563
+ }
564
+ return [line.slice(0, separator), line.slice(separator + 1)];
565
+ })
566
+ .filter((entry) => entry !== undefined));
567
+ }
568
+ function clearPharoMcpLoadStatus(imageState, statusPath) {
569
+ if (!statusPath) {
570
+ return;
571
+ }
572
+ fs.rmSync(statusPath, { force: true });
573
+ delete imageState.pharoMcpLoad;
574
+ }
575
+ function clearDependencyRepositoryDetachStatus(imageState, statusPath) {
576
+ if (!statusPath) {
577
+ return;
578
+ }
579
+ fs.rmSync(statusPath, { force: true });
580
+ delete imageState.dependencyRepositoryDetach;
581
+ }
582
+ function pharoMcpLoadStatusDetails(properties, statusPath) {
583
+ return {
584
+ statusPath,
585
+ ...(properties.source ? { source: properties.source } : {}),
586
+ ...(properties.loadScript ? { loadScript: properties.loadScript } : {}),
587
+ ...(properties.loadPolicy ? { loadPolicy: properties.loadPolicy } : {}),
588
+ ...(properties.repository ? { repository: properties.repository } : {}),
589
+ ...(properties.configuredRepositoryHint
590
+ ? { configuredRepositoryHint: properties.configuredRepositoryHint }
591
+ : {}),
592
+ ...(properties.baseline ? { baseline: properties.baseline } : {}),
593
+ };
594
+ }
595
+ function refreshPharoMcpLoadStatus(imageState, statusPath) {
596
+ if (!statusPath || !fs.existsSync(statusPath)) {
597
+ return undefined;
598
+ }
599
+ const properties = parseStatusProperties(statusPath);
600
+ const status = properties.status;
601
+ const details = pharoMcpLoadStatusDetails(properties, statusPath);
602
+ if (status === "provided" || status === "loaded") {
603
+ imageState.pharoMcpLoad = {
604
+ state: status,
605
+ ...details,
606
+ };
607
+ return undefined;
608
+ }
609
+ if (status === "failed") {
610
+ const message = properties.message ?? "Pharo MCP load failed without a reported message.";
611
+ imageState.pharoMcpLoad = {
612
+ state: "failed",
613
+ ...details,
614
+ error: message,
615
+ };
616
+ return `Pharo MCP load failed for image ${imageState.id}: ${message}`;
617
+ }
618
+ const message = `Invalid Pharo MCP load status at ${statusPath}: ${status ?? "(missing)"}`;
619
+ imageState.pharoMcpLoad = {
620
+ state: "failed",
621
+ ...details,
622
+ error: message,
623
+ };
624
+ return message;
625
+ }
626
+ function dependencyRepositoryDetachRepositories(properties) {
627
+ const byIndex = new Map();
628
+ for (const [key, value] of Object.entries(properties)) {
629
+ const match = /^repository\.(\d+)\.(name|location)$/.exec(key);
630
+ if (!match) {
631
+ continue;
632
+ }
633
+ const index = Number.parseInt(match[1], 10);
634
+ const entry = byIndex.get(index) ?? {};
635
+ entry[match[2]] = value;
636
+ byIndex.set(index, entry);
637
+ }
638
+ return [...byIndex.entries()]
639
+ .sort(([left], [right]) => left - right)
640
+ .map(([, entry]) => entry)
641
+ .filter((entry) => Boolean(entry.location))
642
+ .map((entry) => ({
643
+ location: entry.location,
644
+ ...(entry.name ? { name: entry.name } : {}),
645
+ }));
646
+ }
647
+ function dependencyRepositoryDetachCount(properties, repositories) {
648
+ const parsed = Number.parseInt(properties.detachedCount ?? "", 10);
649
+ return Number.isFinite(parsed) && parsed >= 0 ? parsed : repositories.length;
650
+ }
651
+ function refreshDependencyRepositoryDetachStatus(imageState, statusPath) {
652
+ if (!statusPath || !fs.existsSync(statusPath)) {
653
+ return undefined;
654
+ }
655
+ const properties = parseStatusProperties(statusPath);
656
+ const status = properties.status;
657
+ const repositories = dependencyRepositoryDetachRepositories(properties);
658
+ const details = {
659
+ statusPath,
660
+ ...(properties.cachePath ? { cachePath: properties.cachePath } : {}),
661
+ detachedCount: dependencyRepositoryDetachCount(properties, repositories),
662
+ repositories,
663
+ ...(properties.message ? { message: properties.message } : {}),
664
+ };
665
+ if (status === "detached" || status === "skipped") {
666
+ imageState.dependencyRepositoryDetach = {
667
+ state: status,
668
+ ...details,
669
+ };
670
+ return undefined;
671
+ }
672
+ if (status === "failed") {
673
+ const message = properties.message ??
674
+ "Dependency repository detach failed without a reported message.";
675
+ imageState.dependencyRepositoryDetach = {
676
+ state: "failed",
677
+ ...details,
678
+ error: message,
679
+ };
680
+ return `Dependency repository detach failed for image ${imageState.id}: ${message}`;
681
+ }
682
+ const message = `Invalid dependency repository detach status at ${statusPath}: ${status ?? "(missing)"}`;
683
+ imageState.dependencyRepositoryDetach = {
684
+ state: "failed",
685
+ ...details,
686
+ error: message,
687
+ };
688
+ return message;
689
+ }
690
+ function clearRepositoryWorkspaceLoadStatuses(statusPaths) {
691
+ if (!statusPaths) {
692
+ return;
693
+ }
694
+ for (const statusPath of Object.values(statusPaths)) {
695
+ fs.rmSync(statusPath, { force: true });
696
+ }
697
+ }
698
+ function prepareRepositoryWorkspaceLoadStatuses(imageState, statusPaths) {
699
+ if (!statusPaths) {
700
+ return;
701
+ }
702
+ for (const workspace of projectImageRepositoryWorkspaces(imageState)) {
703
+ const statusPath = statusPaths[workspace.repository.id];
704
+ if (!statusPath) {
705
+ continue;
706
+ }
707
+ workspace.loadState = "pending";
708
+ workspace.loadStatusPath = statusPath;
709
+ workspace.loadSourcePath = joinPathLike(workspace.path, workspace.sourceDirectory);
710
+ delete workspace.loadError;
711
+ }
712
+ }
713
+ function refreshRepositoryWorkspaceLoadStatus(imageState, workspace) {
714
+ if (!workspace?.loadStatusPath) {
715
+ return undefined;
716
+ }
717
+ if (!fs.existsSync(workspace.loadStatusPath)) {
718
+ appendRepositoryWorkspaceDiagnostic(workspace, `Pharo project load has not reported status at ${workspace.loadStatusPath}.`);
719
+ return undefined;
720
+ }
721
+ const properties = parseStatusProperties(workspace.loadStatusPath);
722
+ const status = properties.status;
723
+ workspace.loadSourcePath = properties.sourcePath ?? workspace.loadSourcePath;
724
+ if (properties.message) {
725
+ workspace.loadError = properties.message;
726
+ }
727
+ if (status === "loaded") {
728
+ workspace.loadState = "loaded";
729
+ delete workspace.loadError;
730
+ return undefined;
731
+ }
732
+ if (status === "failed") {
733
+ workspace.loadState = "failed";
734
+ workspace.loadError =
735
+ properties.message ?? "Pharo project load failed without a reported message.";
736
+ appendRepositoryWorkspaceDiagnostic(workspace, workspace.loadError);
737
+ return `Pharo project load failed for image ${imageState.id}: ${workspace.loadError}`;
738
+ }
739
+ workspace.loadState = "failed";
740
+ workspace.loadError = `Invalid Pharo project load status at ${workspace.loadStatusPath}: ${status ?? "(missing)"}`;
741
+ appendRepositoryWorkspaceDiagnostic(workspace, workspace.loadError);
742
+ return workspace.loadError;
743
+ }
744
+ function refreshRepositoryWorkspaceLoadStatuses(imageState) {
745
+ let firstFailure;
746
+ for (const workspace of projectImageRepositoryWorkspaces(imageState)) {
747
+ const failure = refreshRepositoryWorkspaceLoadStatus(imageState, workspace);
748
+ firstFailure ??= failure;
749
+ }
750
+ return firstFailure;
751
+ }
752
+ async function hydrateRepositoryWorkspaceImagePaths(client, imageState, fallbackImagesDirectory) {
753
+ if (!repositoryWorkspaceNeedsLauncherPaths(imageState)) {
754
+ return;
755
+ }
756
+ const infoResult = await client.callTool("pharo_launcher_image_info", {
757
+ imageName: imageState.imageName,
758
+ });
759
+ assertLauncherOk(infoResult, "pharo_launcher_image_info");
760
+ const info = launcherImageInfo(launcherResultData(infoResult));
761
+ const imagesDirectory = info?.imagePath && !isAbsolutePathLike(info.imagePath)
762
+ ? await launcherImagesDirectory(client)
763
+ : undefined;
764
+ applyLauncherImageInfo(imageState, info, imagesDirectory);
765
+ applyLauncherProfileImagePathFallback(imageState, fallbackImagesDirectory);
766
+ }
767
+ async function pollUntil(timeoutMs, intervalMs, sleep, attempt) {
768
+ const startedAt = Date.now();
769
+ while (Date.now() - startedAt <= timeoutMs) {
770
+ const result = await attempt();
771
+ if (result !== undefined) {
772
+ return result;
773
+ }
774
+ await sleep(intervalMs);
775
+ }
776
+ return undefined;
777
+ }
778
+ async function pollProcessForImage(client, imageName, timeoutMs, intervalMs, sleep) {
779
+ return pollUntil(timeoutMs, intervalMs, sleep, async () => {
780
+ return processForImage(client, imageName);
781
+ });
782
+ }
783
+ async function pollStartupProcessForImage(client, imageName, launchedProcess, timeoutMs, intervalMs, sleep) {
784
+ return pollUntil(timeoutMs, intervalMs, sleep, async () => {
785
+ const process = await processForImage(client, imageName);
786
+ if (process) {
787
+ return { kind: "process", process };
788
+ }
789
+ const knownLaunchedProcess = launchedProcess();
790
+ if (knownLaunchedProcess && !isPidAlive(knownLaunchedProcess.pid)) {
791
+ return { kind: "exited", process: knownLaunchedProcess };
792
+ }
793
+ if (knownLaunchedProcess) {
794
+ return { kind: "process", process: knownLaunchedProcess };
795
+ }
796
+ return undefined;
797
+ });
798
+ }
799
+ async function processForImage(client, imageName) {
800
+ const result = await client.callTool("pharo_launcher_process_list", {});
801
+ assertLauncherOk(result, "pharo_launcher_process_list");
802
+ const processes = launcherResultData(result) ?? [];
803
+ return processes.find((process) => processDirectlyMatchesImage(process, imageName));
804
+ }
805
+ function processTimeoutError(imageName) {
806
+ return new Error(`Timed out waiting for PharoLauncher process for image ${imageName}`);
807
+ }
808
+ async function observeLaunchedProcess(options) {
809
+ const launchedProcess = launcherProcessFromResult(options.launcherResult, options.imageName);
810
+ const outcome = await pollStartupProcessForImage(options.processClient, options.imageName, () => launchedProcess, options.timeoutMs, options.intervalMs, options.sleep);
811
+ if (outcome?.kind === "process") {
812
+ return outcome.process;
813
+ }
814
+ if (outcome?.kind === "exited") {
815
+ throw imageStartupExitedBeforeProcessObservedError({
816
+ imageName: options.imageName,
817
+ launcherResult: options.launcherResult,
818
+ process: outcome.process,
819
+ });
820
+ }
821
+ throw processTimeoutError(options.imageName);
822
+ }
823
+ async function pollEndpointHealth(healthClient, endpoint) {
824
+ if (healthClient.checkEndpoint) {
825
+ return healthClient.checkEndpoint(endpoint);
826
+ }
827
+ return healthClient.check(endpoint.port);
828
+ }
829
+ function pharoMcpLoadFailureReadiness(options) {
830
+ const loadFailure = refreshPharoMcpLoadStatus(options.imageState, options.pharoMcpLoadStatusPath);
831
+ if (!loadFailure) {
832
+ return undefined;
833
+ }
834
+ if (options.failOnLoadFailure) {
835
+ throw new Error(loadFailure);
836
+ }
837
+ return { kind: "loadFailed", message: loadFailure };
838
+ }
839
+ async function endpointHandoffReadiness(options) {
840
+ if (!options.preferEndpointHandoff) {
841
+ return undefined;
842
+ }
843
+ const handoff = readImageMcpEndpointHandoff(options.endpointHandoffPath);
844
+ if (handoff.status === "invalid") {
845
+ throw new Error(`Invalid Pharo MCP endpoint handoff at ${handoff.path}: ${handoff.error}`);
846
+ }
847
+ if (handoff.status === "valid" &&
848
+ (await pollEndpointHealth(options.healthClient, handoff.endpoint))) {
849
+ return { kind: "endpoint", endpoint: handoff.endpoint };
850
+ }
851
+ return undefined;
852
+ }
853
+ async function assignedPortReadiness(options) {
854
+ if (options.imageState.assignedPort === undefined) {
855
+ return undefined;
856
+ }
857
+ if (!(await options.healthClient.check(options.imageState.assignedPort))) {
858
+ return undefined;
859
+ }
860
+ return { kind: "assignedPort", port: options.imageState.assignedPort };
861
+ }
862
+ async function processExitReadiness(options) {
863
+ if (!options.processClient || !options.imageName) {
864
+ return undefined;
865
+ }
866
+ const process = await processForImage(options.processClient, options.imageName);
867
+ if (process) {
868
+ return undefined;
869
+ }
870
+ if (!options.launchedProcess) {
871
+ return { kind: "processExited" };
872
+ }
873
+ if (!isPidAlive(options.launchedProcess.pid)) {
874
+ return { kind: "processExited" };
875
+ }
876
+ return undefined;
877
+ }
878
+ async function pollPharoMcpReadiness(options) {
879
+ return pollUntil(options.timeoutMs, options.intervalMs, options.sleep, async () => {
880
+ const loadFailure = pharoMcpLoadFailureReadiness(options);
881
+ if (loadFailure) {
882
+ return loadFailure;
883
+ }
884
+ const handoff = await endpointHandoffReadiness(options);
885
+ if (handoff) {
886
+ return handoff;
887
+ }
888
+ const assignedPort = await assignedPortReadiness(options);
889
+ if (assignedPort) {
890
+ return assignedPort;
891
+ }
892
+ return processExitReadiness(options);
893
+ });
894
+ }
895
+ async function launchImageAndPollProcess(launchClient, processClient, imageName, displayMode, startupScriptPath, timeoutMs, intervalMs, sleep) {
896
+ const launchOutcome = launchClient
897
+ .callTool("pharo_launcher_image_launch", {
898
+ imageName,
899
+ detached: true,
900
+ displayMode,
901
+ script: startupScriptPath,
902
+ })
903
+ .then((result) => ({ kind: "launch", result }), (error) => ({ kind: "launchError", error }));
904
+ const immediateLaunch = await Promise.race([
905
+ launchOutcome,
906
+ new Promise((resolve) => setTimeout(() => resolve(undefined), 0)),
907
+ ]);
908
+ if (immediateLaunch?.kind === "launchError") {
909
+ throw immediateLaunch.error;
910
+ }
911
+ if (immediateLaunch?.kind === "launch") {
912
+ assertLauncherOk(immediateLaunch.result, "pharo_launcher_image_launch");
913
+ return {
914
+ process: await observeLaunchedProcess({
915
+ processClient,
916
+ imageName,
917
+ launcherResult: immediateLaunch.result,
918
+ timeoutMs,
919
+ intervalMs,
920
+ sleep,
921
+ }),
922
+ launcherResult: immediateLaunch.result,
923
+ };
924
+ }
925
+ let launchedProcess;
926
+ const processOutcome = pollStartupProcessForImage(processClient, imageName, () => launchedProcess, timeoutMs, intervalMs, sleep);
927
+ const first = await Promise.race([launchOutcome, processOutcome]);
928
+ if (!first) {
929
+ throw processTimeoutError(imageName);
930
+ }
931
+ if (first.kind === "launchError") {
932
+ throw first.error;
933
+ }
934
+ if (first.kind === "launch") {
935
+ assertLauncherOk(first.result, "pharo_launcher_image_launch");
936
+ launchedProcess = launcherProcessFromResult(first.result, imageName);
937
+ const outcome = await processOutcome;
938
+ if (outcome?.kind === "process") {
939
+ return { process: outcome.process, launcherResult: first.result };
940
+ }
941
+ if (outcome?.kind === "exited") {
942
+ throw imageStartupExitedBeforeProcessObservedError({
943
+ imageName,
944
+ launcherResult: first.result,
945
+ process: outcome.process,
946
+ });
947
+ }
948
+ throw processTimeoutError(imageName);
949
+ }
950
+ if (first.kind === "process") {
951
+ return { process: first.process, launcherResult: undefined };
952
+ }
953
+ throw imageStartupExitedBeforeProcessObservedError({
954
+ imageName,
955
+ launcherResult: undefined,
956
+ process: first.process,
957
+ });
958
+ }
959
+ function imageStartupExitedBeforeProcessObservedError(options) {
960
+ const logPaths = collectLauncherLogPaths(options.launcherResult);
961
+ const logHint = logPaths.length > 0 ? `. Launcher logs: ${logPaths.join(", ")}` : "";
962
+ return new ImageStartupExitedBeforeHealthError(`Image ${options.imageName} process ${options.process.pid} exited before PLexus observed the launcher process${logHint}`, options.launcherResult, options.process);
963
+ }
964
+ function imageStartupExitedBeforeHealthError(options) {
965
+ const endpointHint = options.preferEndpointHandoff
966
+ ? ` or endpoint handoff at ${options.endpointHandoffPath}`
967
+ : "";
968
+ const portHint = options.assignedPort === undefined
969
+ ? ""
970
+ : ` on port ${options.assignedPort}`;
971
+ const logPaths = collectLauncherLogPaths(options.launcherResult);
972
+ const logHint = logPaths.length > 0 ? `. Launcher logs: ${logPaths.join(", ")}` : "";
973
+ return new ImageStartupExitedBeforeHealthError(`Image ${options.imageName} process ${options.process.pid} exited before Pharo MCP became healthy${portHint}${endpointHint}${logHint}`, options.launcherResult, options.process);
974
+ }
975
+ function activeStateImages(state) {
976
+ return state.images.filter((image) => image.status === "starting");
977
+ }
978
+ function imageRequiresPharoMcpHealth(imageConfig, image) {
979
+ return (projectMcpStartupMode(imageConfig.mcp) === "required" &&
980
+ image.pharoMcpContract?.status !== "unsupported");
981
+ }
982
+ function imageCanRouteToPharoMcp(imageConfig, image) {
983
+ return (projectMcpStartupMode(imageConfig.mcp) !== "disabled" &&
984
+ image.pharoMcpContract?.status !== "unsupported");
985
+ }
986
+ async function releaseOptionalPharoMcpRoute(options) {
987
+ if (options.claimsRoot && options.imageState.assignedPort !== undefined) {
988
+ await releaseImagePortClaimIfOwned({
989
+ state: options.state,
990
+ image: options.imageState,
991
+ claimsRoot: options.claimsRoot,
992
+ checks: options.checks,
993
+ });
994
+ }
995
+ delete options.imageState.assignedPort;
996
+ delete options.imageState.mcpEndpoint;
997
+ }
998
+ function applyScopedImageSelection(state, previousState, imageIds) {
999
+ if (!imageIds) {
1000
+ return;
1001
+ }
1002
+ const selectedIds = new Set(imageIds);
1003
+ for (const image of state.images) {
1004
+ if (!selectedIds.has(image.id)) {
1005
+ const previousImage = previousState?.images.find((candidate) => candidate.id === image.id);
1006
+ if (previousImage) {
1007
+ Object.assign(image, previousImage);
1008
+ }
1009
+ else {
1010
+ image.status = "stopped";
1011
+ }
1012
+ }
1013
+ }
1014
+ }
1015
+ function previousImageState(previousState, imageId) {
1016
+ return previousState?.images.find((image) => image.id === imageId);
1017
+ }
1018
+ function shouldMaterializeImageFromHomeCache(options) {
1019
+ return Boolean(options.approval &&
1020
+ projectImageCanUseHomeImageCache(options.imageConfig) &&
1021
+ !previousImageState(options.previousState, options.imageState.id));
1022
+ }
1023
+ function resolveProjectOpenWorkspace(projectRoot, workspaceId) {
1024
+ return workspaceId ? sanitizeRuntimeId(workspaceId) : defaultWorkspaceId(projectRoot);
1025
+ }
1026
+ function resolveProjectOpenSourcePath(options) {
1027
+ return options.requestedSourcePath
1028
+ ? path.resolve(options.requestedSourcePath)
1029
+ : undefined;
1030
+ }
1031
+ function applyProjectImageDisplayMode(imageConfig, imageState, displayMode, requestedDisplayMode) {
1032
+ if (requestedDisplayMode !== undefined ||
1033
+ imageConfig.displayMode !== undefined ||
1034
+ imageState.displayMode !== undefined) {
1035
+ imageState.displayMode = displayMode;
1036
+ }
1037
+ }
1038
+ async function materializeProjectImageForOpen(context, imageConfig, imageState) {
1039
+ const homeMaterialization = shouldMaterializeImageFromHomeCache({
1040
+ previousState: context.previousState,
1041
+ imageConfig,
1042
+ imageState,
1043
+ approval: context.options.homeImageCacheApproval,
1044
+ })
1045
+ ? await materializeProjectImageFromHomeCache({
1046
+ runtimeClient: context.client,
1047
+ homeClient: context.options.homeImageCacheClient ??
1048
+ (context.options.pharoLauncherMcpClient ? context.client : undefined),
1049
+ projectRoot: context.projectRoot,
1050
+ config: context.config,
1051
+ imageConfig,
1052
+ imageState,
1053
+ workspaceId: context.workspaceId,
1054
+ targetId: context.state.targetId,
1055
+ stateRoot: context.resolvedStateRoot,
1056
+ approval: context.options.homeImageCacheApproval,
1057
+ now: context.now,
1058
+ })
1059
+ : undefined;
1060
+ if (!homeMaterialization) {
1061
+ await copyProjectImageFromPreparedCache({
1062
+ client: context.client,
1063
+ projectRoot: context.projectRoot,
1064
+ config: context.config,
1065
+ imageConfig,
1066
+ imageState,
1067
+ approval: context.options.preparedImageCacheApproval,
1068
+ });
1069
+ }
1070
+ await hydrateRepositoryWorkspaceImagePaths(context.client, imageState, context.launcherProfileEnvironment?.PHARO_LAUNCHER_MCP_IMAGES_DIR);
1071
+ materializeProjectImageRepositoryWorkspaces({
1072
+ projectRoot: context.projectRoot,
1073
+ imageConfig,
1074
+ imageState,
1075
+ sourcePath: context.loadSourcePath,
1076
+ });
1077
+ }
1078
+ async function setupProjectImageForOpen(context, imageConfig, imageState, displayMode) {
1079
+ await materializeProjectImageForOpen(context, imageConfig, imageState);
1080
+ const endpointHandoffPath = imageMcpEndpointHandoffPath({
1081
+ projectRoot: context.projectRoot,
1082
+ projectId: context.state.projectId,
1083
+ workspaceId: context.workspaceId,
1084
+ imageId: imageState.id,
1085
+ stateRoot: context.resolvedStateRoot,
1086
+ });
1087
+ removeImageMcpEndpointHandoff(endpointHandoffPath);
1088
+ delete imageState.mcpEndpoint;
1089
+ const startupScript = writeProjectImageStartupScript({
1090
+ projectRoot: context.projectRoot,
1091
+ sourcePath: context.loadSourcePath,
1092
+ config: context.config,
1093
+ imageId: imageState.id,
1094
+ imageState,
1095
+ workspaceId: context.workspaceId,
1096
+ stateRoot: context.resolvedStateRoot,
1097
+ });
1098
+ clearPharoMcpLoadStatus(imageState, startupScript.pharoMcpLoadStatusPath);
1099
+ clearDependencyRepositoryDetachStatus(imageState, startupScript.dependencyRepositoryDetachStatusPath);
1100
+ clearRepositoryWorkspaceLoadStatuses(startupScript.repositoryWorkspaceLoadStatusPaths);
1101
+ prepareRepositoryWorkspaceLoadStatuses(imageState, startupScript.repositoryWorkspaceLoadStatusPaths);
1102
+ const launchClient = context.options.pharoLauncherMcpClient
1103
+ ? context.client
1104
+ : await createStdioPharoLauncherMcpClient(undefined, {
1105
+ profileEnvironment: context.launcherProfileEnvironment,
1106
+ });
1107
+ return {
1108
+ displayMode,
1109
+ endpointHandoffPath,
1110
+ pharoMcpLoadStatusPath: startupScript.pharoMcpLoadStatusPath,
1111
+ dependencyRepositoryDetachStatusPath: startupScript.dependencyRepositoryDetachStatusPath,
1112
+ startupScript,
1113
+ launchClient,
1114
+ ownsLaunchClient: !context.options.pharoLauncherMcpClient,
1115
+ };
1116
+ }
1117
+ function removePreparedPortClaimsForImage(context, imageId) {
1118
+ context.preparedPortClaims = context.preparedPortClaims.filter((candidate) => candidate.imageId !== imageId);
1119
+ }
1120
+ async function recordLaunchedImagePortClaim(context, imageState, pid) {
1121
+ if (!context.claimsRoot) {
1122
+ return;
1123
+ }
1124
+ const preparedClaim = context.preparedPortClaims.find((candidate) => candidate.imageId === imageState.id);
1125
+ if (preparedClaim) {
1126
+ await recordImagePortClaimProcess({
1127
+ claimsRoot: context.claimsRoot,
1128
+ preparedClaim,
1129
+ pid,
1130
+ now: context.now,
1131
+ });
1132
+ }
1133
+ }
1134
+ async function releaseOptionalRouteForImage(context, imageState) {
1135
+ await releaseOptionalPharoMcpRoute({
1136
+ state: context.state,
1137
+ imageState,
1138
+ claimsRoot: context.claimsRoot,
1139
+ checks: context.portClaimChecks,
1140
+ });
1141
+ removePreparedPortClaimsForImage(context, imageState.id);
1142
+ }
1143
+ async function handleMissingPharoMcpReadiness(options) {
1144
+ if (!options.requiresHealth) {
1145
+ await releaseOptionalRouteForImage(options.context, options.imageState);
1146
+ return;
1147
+ }
1148
+ const endpointHint = options.preferEndpointHandoff
1149
+ ? ` or endpoint handoff at ${options.endpointHandoffPath}`
1150
+ : "";
1151
+ const portHint = options.imageState.assignedPort === undefined
1152
+ ? ""
1153
+ : ` on port ${options.imageState.assignedPort}`;
1154
+ throw new Error(`Timed out waiting for Pharo MCP health${portHint}${endpointHint}`);
1155
+ }
1156
+ async function handleEndpointReadiness(options) {
1157
+ options.imageState.mcpEndpoint = options.endpoint;
1158
+ if (options.context.claimsRoot &&
1159
+ options.imageState.assignedPort !== undefined) {
1160
+ await releaseImagePortClaimIfOwned({
1161
+ state: options.context.state,
1162
+ image: options.imageState,
1163
+ claimsRoot: options.context.claimsRoot,
1164
+ checks: options.context.portClaimChecks,
1165
+ });
1166
+ removePreparedPortClaimsForImage(options.context, options.imageState.id);
1167
+ }
1168
+ delete options.imageState.assignedPort;
1169
+ }
1170
+ async function handlePharoMcpReadinessResult(options) {
1171
+ if (!options.readiness) {
1172
+ await handleMissingPharoMcpReadiness(options);
1173
+ return;
1174
+ }
1175
+ if (options.readiness.kind === "processExited") {
1176
+ throw imageStartupExitedBeforeHealthError({
1177
+ imageName: options.imageState.imageName,
1178
+ assignedPort: options.imageState.assignedPort,
1179
+ endpointHandoffPath: options.endpointHandoffPath,
1180
+ preferEndpointHandoff: options.preferEndpointHandoff,
1181
+ launcherResult: options.launchRuntime.launcherResult,
1182
+ process: options.launchRuntime.process,
1183
+ });
1184
+ }
1185
+ if (options.readiness.kind === "loadFailed") {
1186
+ await releaseOptionalRouteForImage(options.context, options.imageState);
1187
+ }
1188
+ if (options.readiness.kind === "endpoint") {
1189
+ await handleEndpointReadiness({
1190
+ context: options.context,
1191
+ imageState: options.imageState,
1192
+ endpoint: options.readiness.endpoint,
1193
+ });
1194
+ }
1195
+ }
1196
+ async function routeProjectImageMcp(options) {
1197
+ if (!imageCanRouteToPharoMcp(options.imageConfig, options.imageState)) {
1198
+ return;
1199
+ }
1200
+ const preferEndpointHandoff = options.imageConfig.mcp.port === undefined;
1201
+ const requiresHealth = imageRequiresPharoMcpHealth(options.imageConfig, options.imageState);
1202
+ const readiness = await pollPharoMcpReadiness({
1203
+ imageState: options.imageState,
1204
+ endpointHandoffPath: options.setup.endpointHandoffPath,
1205
+ preferEndpointHandoff,
1206
+ healthClient: options.context.healthClient,
1207
+ processClient: options.context.client,
1208
+ imageName: options.imageState.imageName,
1209
+ launchedProcess: options.launchRuntime.process,
1210
+ pharoMcpLoadStatusPath: options.setup.pharoMcpLoadStatusPath,
1211
+ failOnLoadFailure: requiresHealth,
1212
+ timeoutMs: requiresHealth ? options.context.poll.healthTimeoutMs : 0,
1213
+ intervalMs: options.context.poll.intervalMs,
1214
+ sleep: options.context.sleep,
1215
+ });
1216
+ await handlePharoMcpReadinessResult({
1217
+ context: options.context,
1218
+ imageState: options.imageState,
1219
+ readiness,
1220
+ endpointHandoffPath: options.setup.endpointHandoffPath,
1221
+ preferEndpointHandoff,
1222
+ requiresHealth,
1223
+ launchRuntime: options.launchRuntime,
1224
+ });
1225
+ }
1226
+ function assertProjectImageLoadStatuses(options) {
1227
+ const pharoMcpLoadFailure = refreshPharoMcpLoadStatus(options.imageState, options.pharoMcpLoadStatusPath);
1228
+ if (pharoMcpLoadFailure &&
1229
+ imageRequiresPharoMcpHealth(options.imageConfig, options.imageState)) {
1230
+ throw new Error(pharoMcpLoadFailure);
1231
+ }
1232
+ const loadFailure = refreshRepositoryWorkspaceLoadStatuses(options.imageState);
1233
+ if (loadFailure) {
1234
+ throw new Error(loadFailure);
1235
+ }
1236
+ const detachFailure = refreshDependencyRepositoryDetachStatus(options.imageState, options.dependencyRepositoryDetachStatusPath);
1237
+ if (detachFailure) {
1238
+ throw new Error(detachFailure);
1239
+ }
1240
+ }
1241
+ async function ensureProjectImageRepositoryWorkspaces(options) {
1242
+ for (const workspace of projectImageRepositoryWorkspaces(options.imageState)) {
1243
+ await ensureRepositoryWorkspaceRegistered({
1244
+ imageConfig: options.imageConfig,
1245
+ imageState: options.imageState,
1246
+ workspace,
1247
+ imageMcpClient: options.imageMcpClient,
1248
+ });
1249
+ }
1250
+ }
1251
+ async function launchProjectImage(options) {
1252
+ const { context, imageConfig, imageState, setup } = options;
1253
+ try {
1254
+ const launchRuntime = await launchImageAndPollProcess(setup.launchClient, context.client, imageState.imageName, setup.displayMode, setup.startupScript.filePath, context.poll.processTimeoutMs, context.poll.intervalMs, context.sleep);
1255
+ const process = launchRuntime.process;
1256
+ imageState.pid = process.pid;
1257
+ await recordLaunchedImagePortClaim(context, imageState, process.pid);
1258
+ await routeProjectImageMcp({
1259
+ context,
1260
+ imageConfig,
1261
+ imageState,
1262
+ setup,
1263
+ launchRuntime,
1264
+ });
1265
+ assertProjectImageLoadStatuses({
1266
+ imageConfig,
1267
+ imageState,
1268
+ pharoMcpLoadStatusPath: setup.pharoMcpLoadStatusPath,
1269
+ dependencyRepositoryDetachStatusPath: setup.dependencyRepositoryDetachStatusPath,
1270
+ });
1271
+ await ensureProjectImageRepositoryWorkspaces({
1272
+ imageConfig,
1273
+ imageState,
1274
+ imageMcpClient: context.imageMcpClient,
1275
+ });
1276
+ }
1277
+ finally {
1278
+ if (setup.ownsLaunchClient) {
1279
+ closeClientQuietly(setup.launchClient);
1280
+ }
1281
+ }
1282
+ }
1283
+ async function releaseCreatedPreparedPortClaim(context, imageState) {
1284
+ if (!context.claimsRoot) {
1285
+ return;
1286
+ }
1287
+ const claim = context.preparedPortClaims.find((candidate) => candidate.imageId === imageState.id);
1288
+ if (claim?.created) {
1289
+ await releasePreparedImagePortClaims(context.claimsRoot, [claim]);
1290
+ context.preparedPortClaims = context.preparedPortClaims.filter((candidate) => candidate !== claim);
1291
+ }
1292
+ }
1293
+ async function recordProjectImageOpenFailure(options) {
1294
+ options.imageState.status = "failed";
1295
+ await releaseCreatedPreparedPortClaim(options.context, options.imageState);
1296
+ const pharoMcpLoadFailure = refreshPharoMcpLoadStatus(options.imageState, options.setup?.pharoMcpLoadStatusPath);
1297
+ const loadFailure = refreshRepositoryWorkspaceLoadStatuses(options.imageState);
1298
+ const detachFailure = refreshDependencyRepositoryDetachStatus(options.imageState, options.setup?.dependencyRepositoryDetachStatusPath);
1299
+ options.context.failures.push({
1300
+ imageId: options.imageState.id,
1301
+ imageName: options.imageState.imageName,
1302
+ message: detachFailure ??
1303
+ loadFailure ??
1304
+ pharoMcpLoadFailure ??
1305
+ errorMessage(options.error),
1306
+ ...(detachFailure || loadFailure || pharoMcpLoadFailure
1307
+ ? {}
1308
+ : launcherFailureDetails(options.error)),
1309
+ ...(detachFailure || loadFailure || pharoMcpLoadFailure
1310
+ ? {}
1311
+ : startupFailureDetails(options.error)),
1312
+ });
1313
+ }
1314
+ async function openProjectImage(context, imageState) {
1315
+ const imageConfig = context.config.images.find((image) => image.id === imageState.id);
1316
+ if (!imageConfig) {
1317
+ return;
1318
+ }
1319
+ const displayMode = context.options.displayMode ?? projectImageDisplayMode(imageConfig);
1320
+ applyProjectImageDisplayMode(imageConfig, imageState, displayMode, context.options.displayMode);
1321
+ let setup;
1322
+ try {
1323
+ setup = await setupProjectImageForOpen(context, imageConfig, imageState, displayMode);
1324
+ await launchProjectImage({ context, imageConfig, imageState, setup });
1325
+ imageState.status = "running";
1326
+ }
1327
+ catch (error) {
1328
+ await recordProjectImageOpenFailure({ context, imageState, setup, error });
1329
+ }
1330
+ }
1331
+ async function openActiveProjectImages(context, imagesToOpen) {
1332
+ for (const imageState of imagesToOpen) {
1333
+ await openProjectImage(context, imageState);
1334
+ }
1335
+ }
1336
+ export async function openProject(options) {
1337
+ const projectRoot = path.resolve(options.projectRoot);
1338
+ const config = loadProjectConfig(projectRoot);
1339
+ const workspaceId = resolveProjectOpenWorkspace(projectRoot, options.workspaceId);
1340
+ const statePath = projectStatePathForConfig({
1341
+ projectRoot,
1342
+ config,
1343
+ workspaceId,
1344
+ stateRoot: options.stateRoot,
1345
+ });
1346
+ const resolvedStateRoot = projectStateRootForConfig(config, options.stateRoot);
1347
+ const previousState = loadProjectState(statePath);
1348
+ const requestedSourcePath = options.sourcePath ?? previousState?.sourcePath;
1349
+ const sourcePath = resolveProjectOpenSourcePath({
1350
+ requestedSourcePath,
1351
+ projectRoot,
1352
+ });
1353
+ const loadSourcePath = sourcePath ?? projectRoot;
1354
+ const now = options.now ?? (() => new Date());
1355
+ const runtime = resolveProjectRuntimePolicy(config);
1356
+ const portRange = options.portRange ?? runtime.imagePorts.range;
1357
+ const claimsRoot = imagePortClaimsRootForConfig(projectRoot, config);
1358
+ const projectReservedOwners = collectReservedProjectPortOwners({
1359
+ projectRoot,
1360
+ projectId: projectConfigId(config),
1361
+ stateRoot: resolvedStateRoot,
1362
+ excludeWorkspaceId: workspaceId,
1363
+ });
1364
+ const state = createProjectState(config, {
1365
+ updatedAt: now().toISOString(),
1366
+ previousState,
1367
+ workspaceId,
1368
+ targetId: options.targetId,
1369
+ sourcePath,
1370
+ reservedPorts: claimsRoot
1371
+ ? projectReservedOwners.map((owner) => owner.port)
1372
+ : undefined,
1373
+ });
1374
+ applyScopedImageSelection(state, previousState, options.imageIds);
1375
+ const imagesToOpen = activeStateImages(state);
1376
+ const failures = [];
1377
+ if (imagesToOpen.length === 0) {
1378
+ state.runtimeStatus = runtimeStatusForImages(state.images);
1379
+ state.updatedAt = now().toISOString();
1380
+ saveProjectState(statePath, state);
1381
+ return {
1382
+ ok: true,
1383
+ projectRoot,
1384
+ statePath,
1385
+ state,
1386
+ failures,
1387
+ };
1388
+ }
1389
+ const portClaimChecks = options.portClaimChecks ?? defaultImagePortClaimChecks();
1390
+ const launcherProfileEnvironment = pharoLauncherMcpProfileEnvironment({
1391
+ projectRoot,
1392
+ config,
1393
+ workspaceId,
1394
+ targetId: state.targetId,
1395
+ stateRoot: resolvedStateRoot,
1396
+ });
1397
+ let preparedPortClaims = [];
1398
+ if (claimsRoot) {
1399
+ preparedPortClaims = await prepareImagePortClaims({
1400
+ config,
1401
+ state,
1402
+ previousState,
1403
+ images: imagesToOpen,
1404
+ projectReservedOwners,
1405
+ claimsRoot,
1406
+ portRange,
1407
+ checks: portClaimChecks,
1408
+ now,
1409
+ });
1410
+ }
1411
+ const client = options.pharoLauncherMcpClient ??
1412
+ (await createStdioPharoLauncherMcpClient(undefined, {
1413
+ profileEnvironment: launcherProfileEnvironment,
1414
+ }));
1415
+ const ownsClient = !options.pharoLauncherMcpClient;
1416
+ const healthClient = options.healthClient ?? new HttpPharoMcpHealthClient();
1417
+ const imageMcpClient = options.imageMcpClient ?? new HttpProjectOpenImageMcpClient();
1418
+ const poll = {
1419
+ intervalMs: options.poll?.intervalMs ?? 500,
1420
+ processTimeoutMs: options.poll?.processTimeoutMs ?? 30_000,
1421
+ healthTimeoutMs: options.poll?.healthTimeoutMs ?? 5 * 60_000,
1422
+ };
1423
+ const sleep = options.sleep ?? defaultSleep;
1424
+ const context = {
1425
+ options,
1426
+ projectRoot,
1427
+ config,
1428
+ previousState,
1429
+ sourcePath,
1430
+ loadSourcePath,
1431
+ workspaceId,
1432
+ resolvedStateRoot,
1433
+ statePath,
1434
+ state,
1435
+ claimsRoot,
1436
+ projectReservedOwners,
1437
+ portClaimChecks,
1438
+ launcherProfileEnvironment,
1439
+ preparedPortClaims,
1440
+ client,
1441
+ ownsClient,
1442
+ healthClient,
1443
+ imageMcpClient,
1444
+ poll,
1445
+ sleep,
1446
+ failures,
1447
+ now,
1448
+ };
1449
+ try {
1450
+ await openActiveProjectImages(context, imagesToOpen);
1451
+ state.runtimeStatus = runtimeStatusForImages(state.images);
1452
+ state.updatedAt = now().toISOString();
1453
+ saveProjectState(statePath, state);
1454
+ const result = {
1455
+ ok: failures.length === 0,
1456
+ projectRoot,
1457
+ statePath,
1458
+ state,
1459
+ failures,
1460
+ };
1461
+ if (!result.ok) {
1462
+ throw new ProjectOpenError("One or more project images failed to open", result);
1463
+ }
1464
+ return result;
1465
+ }
1466
+ finally {
1467
+ if (context.ownsClient) {
1468
+ await client.close?.();
1469
+ }
1470
+ }
1471
+ }
1472
+ //# sourceMappingURL=projectOpen.js.map