@evref-bl/plexus 0.15.2 → 0.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (251) hide show
  1. package/README.md +8 -12
  2. package/dist/cli.js +8 -183
  3. package/dist/cli.js.map +1 -1
  4. package/dist/commandLine.d.ts +13 -0
  5. package/dist/commandLine.d.ts.map +1 -0
  6. package/dist/commandLine.js +247 -0
  7. package/dist/commandLine.js.map +1 -0
  8. package/dist/config/pharoMcpVersion.d.ts +6 -7
  9. package/dist/config/pharoMcpVersion.d.ts.map +1 -1
  10. package/dist/config/pharoMcpVersion.js +6 -7
  11. package/dist/config/pharoMcpVersion.js.map +1 -1
  12. package/dist/errors.d.ts +11 -0
  13. package/dist/errors.d.ts.map +1 -0
  14. package/dist/errors.js +17 -0
  15. package/dist/errors.js.map +1 -0
  16. package/dist/forward/endpointHandoffFormat.d.ts +23 -0
  17. package/dist/forward/endpointHandoffFormat.d.ts.map +1 -0
  18. package/dist/forward/endpointHandoffFormat.js.map +1 -0
  19. package/dist/forward/index.d.ts +20 -0
  20. package/dist/forward/index.d.ts.map +1 -0
  21. package/dist/forward/index.js +77 -0
  22. package/dist/forward/index.js.map +1 -0
  23. package/dist/forward/jsonRpc.d.ts +20 -0
  24. package/dist/forward/jsonRpc.d.ts.map +1 -0
  25. package/dist/forward/jsonRpc.js +141 -0
  26. package/dist/forward/jsonRpc.js.map +1 -0
  27. package/dist/home.d.ts +15 -0
  28. package/dist/home.d.ts.map +1 -0
  29. package/dist/home.js +30 -0
  30. package/dist/home.js.map +1 -0
  31. package/dist/images/bases.d.ts +40 -0
  32. package/dist/images/bases.d.ts.map +1 -0
  33. package/dist/images/bases.js +190 -0
  34. package/dist/images/bases.js.map +1 -0
  35. package/dist/images/claims.d.ts +34 -0
  36. package/dist/images/claims.d.ts.map +1 -0
  37. package/dist/images/claims.js +119 -0
  38. package/dist/images/claims.js.map +1 -0
  39. package/dist/images/context.d.ts +22 -0
  40. package/dist/images/context.d.ts.map +1 -0
  41. package/dist/images/context.js +26 -0
  42. package/dist/images/context.js.map +1 -0
  43. package/dist/images/create.d.ts +19 -0
  44. package/dist/images/create.d.ts.map +1 -0
  45. package/dist/images/create.js +121 -0
  46. package/dist/images/create.js.map +1 -0
  47. package/dist/images/delete.d.ts +10 -0
  48. package/dist/images/delete.d.ts.map +1 -0
  49. package/dist/images/delete.js +31 -0
  50. package/dist/images/delete.js.map +1 -0
  51. package/dist/images/endpoint.d.ts +17 -0
  52. package/dist/images/endpoint.d.ts.map +1 -0
  53. package/dist/images/endpoint.js +58 -0
  54. package/dist/images/endpoint.js.map +1 -0
  55. package/dist/images/index.d.ts +28 -0
  56. package/dist/images/index.d.ts.map +1 -0
  57. package/dist/images/index.js +51 -0
  58. package/dist/images/index.js.map +1 -0
  59. package/dist/images/leftovers.d.ts +9 -0
  60. package/dist/images/leftovers.d.ts.map +1 -0
  61. package/dist/images/leftovers.js +38 -0
  62. package/dist/images/leftovers.js.map +1 -0
  63. package/dist/images/list.d.ts +12 -0
  64. package/dist/images/list.d.ts.map +1 -0
  65. package/dist/images/list.js +74 -0
  66. package/dist/images/list.js.map +1 -0
  67. package/dist/images/names.d.ts +15 -0
  68. package/dist/images/names.d.ts.map +1 -0
  69. package/dist/images/names.js +53 -0
  70. package/dist/images/names.js.map +1 -0
  71. package/dist/images/prepare.d.ts +18 -0
  72. package/dist/images/prepare.d.ts.map +1 -0
  73. package/dist/images/prepare.js +58 -0
  74. package/dist/images/prepare.js.map +1 -0
  75. package/dist/images/processes.d.ts +21 -0
  76. package/dist/images/processes.d.ts.map +1 -0
  77. package/dist/images/processes.js +83 -0
  78. package/dist/images/processes.js.map +1 -0
  79. package/dist/images/scripts.d.ts +39 -0
  80. package/dist/images/scripts.d.ts.map +1 -0
  81. package/dist/images/scripts.js +127 -0
  82. package/dist/images/scripts.js.map +1 -0
  83. package/dist/images/start.d.ts +23 -0
  84. package/dist/images/start.d.ts.map +1 -0
  85. package/dist/images/start.js +173 -0
  86. package/dist/images/start.js.map +1 -0
  87. package/dist/images/stop.d.ts +11 -0
  88. package/dist/images/stop.d.ts.map +1 -0
  89. package/dist/images/stop.js +42 -0
  90. package/dist/images/stop.js.map +1 -0
  91. package/dist/images/store.d.ts +62 -0
  92. package/dist/images/store.d.ts.map +1 -0
  93. package/dist/images/store.js +180 -0
  94. package/dist/images/store.js.map +1 -0
  95. package/dist/images/templates.d.ts +14 -0
  96. package/dist/images/templates.d.ts.map +1 -0
  97. package/dist/images/templates.js +84 -0
  98. package/dist/images/templates.js.map +1 -0
  99. package/dist/index.d.ts +12 -22
  100. package/dist/index.d.ts.map +1 -1
  101. package/dist/index.js +8 -22
  102. package/dist/index.js.map +1 -1
  103. package/dist/launcher/pharoLauncherMcpClient.d.ts +22 -59
  104. package/dist/launcher/pharoLauncherMcpClient.d.ts.map +1 -1
  105. package/dist/launcher/pharoLauncherMcpClient.js +121 -98
  106. package/dist/launcher/pharoLauncherMcpClient.js.map +1 -1
  107. package/dist/launcher/pharoLauncherProfile.d.ts +5 -32
  108. package/dist/launcher/pharoLauncherProfile.d.ts.map +1 -1
  109. package/dist/launcher/pharoLauncherProfile.js +17 -115
  110. package/dist/launcher/pharoLauncherProfile.js.map +1 -1
  111. package/dist/mcp/server.d.ts +18 -0
  112. package/dist/mcp/server.d.ts.map +1 -0
  113. package/dist/mcp/server.js +206 -0
  114. package/dist/mcp/server.js.map +1 -0
  115. package/dist/types.d.ts +68 -0
  116. package/dist/types.d.ts.map +1 -0
  117. package/dist/types.js +2 -0
  118. package/dist/types.js.map +1 -0
  119. package/dist/version.d.ts +2 -0
  120. package/dist/version.d.ts.map +1 -0
  121. package/dist/version.js +5 -0
  122. package/dist/version.js.map +1 -0
  123. package/package.json +3 -12
  124. package/dist/config/config.d.ts +0 -15
  125. package/dist/config/config.d.ts.map +0 -1
  126. package/dist/config/config.js +0 -74
  127. package/dist/config/config.js.map +0 -1
  128. package/dist/config/plexusHome.d.ts +0 -17
  129. package/dist/config/plexusHome.d.ts.map +0 -1
  130. package/dist/config/plexusHome.js +0 -30
  131. package/dist/config/plexusHome.js.map +0 -1
  132. package/dist/config/projectConfig.d.ts +0 -141
  133. package/dist/config/projectConfig.d.ts.map +0 -1
  134. package/dist/config/projectConfig.js +0 -722
  135. package/dist/config/projectConfig.js.map +0 -1
  136. package/dist/config/projectConfigAuthoring.d.ts +0 -53
  137. package/dist/config/projectConfigAuthoring.d.ts.map +0 -1
  138. package/dist/config/projectConfigAuthoring.js +0 -159
  139. package/dist/config/projectConfigAuthoring.js.map +0 -1
  140. package/dist/gateway/projectImageMcpEndpoint.d.ts +0 -23
  141. package/dist/gateway/projectImageMcpEndpoint.d.ts.map +0 -1
  142. package/dist/gateway/projectImageMcpEndpoint.js +0 -40
  143. package/dist/gateway/projectImageMcpEndpoint.js.map +0 -1
  144. package/dist/gateway/server/index.d.ts +0 -8
  145. package/dist/gateway/server/index.d.ts.map +0 -1
  146. package/dist/gateway/server/index.js +0 -34
  147. package/dist/gateway/server/index.js.map +0 -1
  148. package/dist/gateway/server/mcp/server.d.ts +0 -66
  149. package/dist/gateway/server/mcp/server.d.ts.map +0 -1
  150. package/dist/gateway/server/mcp/server.js +0 -458
  151. package/dist/gateway/server/mcp/server.js.map +0 -1
  152. package/dist/gateway/server/routing/endpointHandoffFormat.d.ts +0 -26
  153. package/dist/gateway/server/routing/endpointHandoffFormat.d.ts.map +0 -1
  154. package/dist/gateway/server/routing/endpointHandoffFormat.js.map +0 -1
  155. package/dist/gateway/server/routing/gateway.d.ts +0 -167
  156. package/dist/gateway/server/routing/gateway.d.ts.map +0 -1
  157. package/dist/gateway/server/routing/gateway.js +0 -863
  158. package/dist/gateway/server/routing/gateway.js.map +0 -1
  159. package/dist/gateway/server/routing/imageMcpRouter.d.ts +0 -59
  160. package/dist/gateway/server/routing/imageMcpRouter.d.ts.map +0 -1
  161. package/dist/gateway/server/routing/imageMcpRouter.js +0 -253
  162. package/dist/gateway/server/routing/imageMcpRouter.js.map +0 -1
  163. package/dist/gateway/server/routing/pharoFacade.d.ts +0 -12
  164. package/dist/gateway/server/routing/pharoFacade.d.ts.map +0 -1
  165. package/dist/gateway/server/routing/pharoFacade.js +0 -67
  166. package/dist/gateway/server/routing/pharoFacade.js.map +0 -1
  167. package/dist/gateway/server/routing/routeDiscovery.d.ts +0 -26
  168. package/dist/gateway/server/routing/routeDiscovery.d.ts.map +0 -1
  169. package/dist/gateway/server/routing/routeDiscovery.js +0 -46
  170. package/dist/gateway/server/routing/routeDiscovery.js.map +0 -1
  171. package/dist/gateway/server/routing/routingTable.d.ts +0 -120
  172. package/dist/gateway/server/routing/routingTable.d.ts.map +0 -1
  173. package/dist/gateway/server/routing/routingTable.js +0 -215
  174. package/dist/gateway/server/routing/routingTable.js.map +0 -1
  175. package/dist/gateway/server/support/processLiveness.d.ts +0 -10
  176. package/dist/gateway/server/support/processLiveness.d.ts.map +0 -1
  177. package/dist/gateway/server/support/processLiveness.js +0 -25
  178. package/dist/gateway/server/support/processLiveness.js.map +0 -1
  179. package/dist/gateway/server/support/sourceBuildPreflight.d.ts +0 -15
  180. package/dist/gateway/server/support/sourceBuildPreflight.d.ts.map +0 -1
  181. package/dist/gateway/server/support/sourceBuildPreflight.js +0 -88
  182. package/dist/gateway/server/support/sourceBuildPreflight.js.map +0 -1
  183. package/dist/gateway/server/support/toolResultFormatting.d.ts +0 -8
  184. package/dist/gateway/server/support/toolResultFormatting.d.ts.map +0 -1
  185. package/dist/gateway/server/support/toolResultFormatting.js +0 -74
  186. package/dist/gateway/server/support/toolResultFormatting.js.map +0 -1
  187. package/dist/images/homeImageCache.d.ts +0 -302
  188. package/dist/images/homeImageCache.d.ts.map +0 -1
  189. package/dist/images/homeImageCache.js +0 -1031
  190. package/dist/images/homeImageCache.js.map +0 -1
  191. package/dist/images/imageRescue.d.ts +0 -151
  192. package/dist/images/imageRescue.d.ts.map +0 -1
  193. package/dist/images/imageRescue.js +0 -748
  194. package/dist/images/imageRescue.js.map +0 -1
  195. package/dist/images/imageRuntime.d.ts +0 -60
  196. package/dist/images/imageRuntime.d.ts.map +0 -1
  197. package/dist/images/imageRuntime.js +0 -90
  198. package/dist/images/imageRuntime.js.map +0 -1
  199. package/dist/images/preparedImageCache.d.ts +0 -86
  200. package/dist/images/preparedImageCache.d.ts.map +0 -1
  201. package/dist/images/preparedImageCache.js +0 -229
  202. package/dist/images/preparedImageCache.js.map +0 -1
  203. package/dist/images/scopedTemplateCatalog.d.ts +0 -33
  204. package/dist/images/scopedTemplateCatalog.d.ts.map +0 -1
  205. package/dist/images/scopedTemplateCatalog.js +0 -363
  206. package/dist/images/scopedTemplateCatalog.js.map +0 -1
  207. package/dist/internal.d.ts +0 -20
  208. package/dist/internal.d.ts.map +0 -1
  209. package/dist/internal.js +0 -20
  210. package/dist/internal.js.map +0 -1
  211. package/dist/launcher/scopedPharoLauncherServer.d.ts +0 -349
  212. package/dist/launcher/scopedPharoLauncherServer.d.ts.map +0 -1
  213. package/dist/launcher/scopedPharoLauncherServer.js +0 -1307
  214. package/dist/launcher/scopedPharoLauncherServer.js.map +0 -1
  215. package/dist/lifecycle/startProjectImage.d.ts +0 -94
  216. package/dist/lifecycle/startProjectImage.d.ts.map +0 -1
  217. package/dist/lifecycle/startProjectImage.js +0 -1054
  218. package/dist/lifecycle/startProjectImage.js.map +0 -1
  219. package/dist/lifecycle/stopProjectImage.d.ts +0 -31
  220. package/dist/lifecycle/stopProjectImage.d.ts.map +0 -1
  221. package/dist/lifecycle/stopProjectImage.js +0 -201
  222. package/dist/lifecycle/stopProjectImage.js.map +0 -1
  223. package/dist/mcp/agentServer.d.ts +0 -15
  224. package/dist/mcp/agentServer.d.ts.map +0 -1
  225. package/dist/mcp/agentServer.js +0 -67
  226. package/dist/mcp/agentServer.js.map +0 -1
  227. package/dist/mcp/imageOperations.d.ts +0 -54
  228. package/dist/mcp/imageOperations.d.ts.map +0 -1
  229. package/dist/mcp/imageOperations.js +0 -223
  230. package/dist/mcp/imageOperations.js.map +0 -1
  231. package/dist/mcp/pharoMcpHealth.d.ts +0 -26
  232. package/dist/mcp/pharoMcpHealth.d.ts.map +0 -1
  233. package/dist/mcp/pharoMcpHealth.js +0 -97
  234. package/dist/mcp/pharoMcpHealth.js.map +0 -1
  235. package/dist/support/pathStyle.d.ts +0 -11
  236. package/dist/support/pathStyle.d.ts.map +0 -1
  237. package/dist/support/pathStyle.js +0 -61
  238. package/dist/support/pathStyle.js.map +0 -1
  239. package/dist/support/toolResultFormatting.d.ts +0 -8
  240. package/dist/support/toolResultFormatting.d.ts.map +0 -1
  241. package/dist/support/toolResultFormatting.js +0 -74
  242. package/dist/support/toolResultFormatting.js.map +0 -1
  243. package/dist/workspace/projectStartupScript.d.ts +0 -73
  244. package/dist/workspace/projectStartupScript.d.ts.map +0 -1
  245. package/dist/workspace/projectStartupScript.js +0 -607
  246. package/dist/workspace/projectStartupScript.js.map +0 -1
  247. package/dist/workspace/projectState.d.ts +0 -216
  248. package/dist/workspace/projectState.d.ts.map +0 -1
  249. package/dist/workspace/projectState.js +0 -172
  250. package/dist/workspace/projectState.js.map +0 -1
  251. /package/dist/{gateway/server/routing → forward}/endpointHandoffFormat.js +0 -0
@@ -1,1031 +0,0 @@
1
- import crypto from "node:crypto";
2
- import fs from "node:fs";
3
- import { imageFileExists } from "./imageRuntime.js";
4
- import { prepareScopedTemplateCatalog } from "./scopedTemplateCatalog.js";
5
- import { defaultPharoMcpMetacelloRepository, pharoMcpMetacelloRepositoryLocation, } from "../workspace/projectStartupScript.js";
6
- import { projectMcpStartupMode, resolveProjectRuntimePolicy, } from "../config/projectConfig.js";
7
- import { homeImageCacheDirectoryName, homeImageCacheEnabled, homeImageCacheNetworkPolicy, resolvePlexusHomePath, } from "../config/plexusHome.js";
8
- import { dirnamePathLike, isAbsolutePathLike, joinPathLike, resolvePathLike, } from "../support/pathStyle.js";
9
- import { homeProfilesRoot, pharoLauncherMcpProfileEnvironment, } from "../launcher/pharoLauncherProfile.js";
10
- import { openPharoLauncherClient, } from "../launcher/pharoLauncherMcpClient.js";
11
- export const homeImageCacheSchemaVersion = 1;
12
- export class HomeImageCacheError extends Error {
13
- constructor(message) {
14
- super(message);
15
- this.name = "HomeImageCacheError";
16
- }
17
- }
18
- function removeUndefined(value) {
19
- if (Array.isArray(value)) {
20
- return value.map(removeUndefined);
21
- }
22
- if (value && typeof value === "object") {
23
- const entries = Object.entries(value)
24
- .filter(([, entryValue]) => entryValue !== undefined)
25
- .map(([key, entryValue]) => [key, removeUndefined(entryValue)])
26
- .sort(([left], [right]) => left.localeCompare(right));
27
- return Object.fromEntries(entries);
28
- }
29
- return value;
30
- }
31
- function stableJson(value) {
32
- return JSON.stringify(removeUndefined(value));
33
- }
34
- function sha256Hex(value) {
35
- return crypto.createHash("sha256").update(value).digest("hex");
36
- }
37
- function safeCacheKey(value) {
38
- if (!/^[a-f0-9]{64}$/.test(value)) {
39
- throw new HomeImageCacheError(`Invalid home image cache key: ${value}`);
40
- }
41
- return value;
42
- }
43
- function toMetacelloRepository(repository) {
44
- return repository ?? defaultPharoMcpMetacelloRepository;
45
- }
46
- function resolveMcpLoadScriptPath(projectRoot, mcp) {
47
- return isAbsolutePathLike(mcp.loadScript)
48
- ? resolvePathLike(mcp.loadScript)
49
- : resolvePathLike(projectRoot, mcp.loadScript);
50
- }
51
- function sourceFromProjectImage(config, imageConfig) {
52
- if (imageConfig.preparedImage?.cacheId) {
53
- const preparedImage = config.preparedImages?.find((candidate) => candidate.id === imageConfig.preparedImage?.cacheId);
54
- if (!preparedImage) {
55
- throw new HomeImageCacheError(`Project image ${imageConfig.id} references unknown prepared image cache: ${imageConfig.preparedImage.cacheId}`);
56
- }
57
- return {
58
- source: preparedSource(preparedImage),
59
- mcp: preparedImage.mcp,
60
- };
61
- }
62
- if (imageConfig.create) {
63
- return {
64
- source: createSource(imageConfig.create),
65
- mcp: imageConfig.mcp,
66
- };
67
- }
68
- throw new HomeImageCacheError(`Project image ${imageConfig.id} has no template create or prepared image source`);
69
- }
70
- /**
71
- * What preparing a home image cache base for this image would load now,
72
- * decided as the preparation decides it. Compared with what an image's base
73
- * loaded, it says whether an MCP the image already had is the one the project
74
- * loads. Undefined when the image has no source a base is made from.
75
- */
76
- export function projectImagePharoMcpLoad(options) {
77
- if (!projectImageCanUseHomeImageCache(options.imageConfig)) {
78
- return undefined;
79
- }
80
- return pharoMcpLoad(options.projectRoot, sourceFromProjectImage(options.config, options.imageConfig).mcp);
81
- }
82
- /**
83
- * Records on an image the base it was just copied from and what preparing that
84
- * base loaded, so a later start can say whether the MCP the image already has
85
- * is the one the project loads. An image made any other way gets no base.
86
- */
87
- export function recordHomeImageCacheBase(imageState, materialization) {
88
- const plan = materialization?.plan;
89
- if (plan?.runtimeCopy && materialization?.operations.includes(plan.runtimeCopy)) {
90
- const load = plan.keyMaterial.pharoMcp.load;
91
- imageState.homeImageCacheBase = {
92
- key: plan.key,
93
- ...(load ? { pharoMcpLoad: load } : {}),
94
- };
95
- return;
96
- }
97
- delete imageState.homeImageCacheBase;
98
- }
99
- export function sameHomeImageCachePharoMcpLoad(left, right) {
100
- return stableJson(left) === stableJson(right);
101
- }
102
- export function projectImageCanUseHomeImageCache(imageConfig) {
103
- return Boolean(imageConfig.create || imageConfig.preparedImage?.cacheId);
104
- }
105
- function createSource(source) {
106
- return {
107
- kind: "template",
108
- ...(source.profileId ? { profileId: source.profileId } : {}),
109
- templateName: source.templateName,
110
- ...(source.templateCategory
111
- ? { templateCategory: source.templateCategory }
112
- : {}),
113
- };
114
- }
115
- function preparedSource(preparedImage) {
116
- return preparedTemplateSource(preparedImage.source);
117
- }
118
- function preparedTemplateSource(source) {
119
- return {
120
- kind: "template",
121
- ...(source.profileId ? { profileId: source.profileId } : {}),
122
- templateName: source.templateName,
123
- ...(source.templateCategory
124
- ? { templateCategory: source.templateCategory }
125
- : {}),
126
- };
127
- }
128
- export function homeImageCacheRootPath(homePath) {
129
- return joinPathLike(homePath, homeImageCacheDirectoryName);
130
- }
131
- export function homeImageCacheEntryDirectory(cacheRoot, key) {
132
- return joinPathLike(cacheRoot, "entries", safeCacheKey(key));
133
- }
134
- export function homeImageCacheManifestPath(cacheRoot, key) {
135
- return joinPathLike(homeImageCacheEntryDirectory(cacheRoot, key), "manifest.json");
136
- }
137
- export function homeImageCacheLockPath(cacheRoot, key) {
138
- return joinPathLike(cacheRoot, "locks", safeCacheKey(key));
139
- }
140
- export function homeImageCachePreparationScriptPath(cacheRoot, key) {
141
- return joinPathLike(homeImageCacheEntryDirectory(cacheRoot, key), "prepare.st");
142
- }
143
- export function homeImageCachePreparationStatusPath(cacheRoot, key) {
144
- return joinPathLike(homeImageCacheEntryDirectory(cacheRoot, key), "preparation-status.properties");
145
- }
146
- export function homeImageCacheImageName(key) {
147
- return `PlexusHomeCache-${safeCacheKey(key).slice(0, 24)}`;
148
- }
149
- export function homeImageCacheProfile(homePath) {
150
- const stateRoot = joinPathLike(homeProfilesRoot(homePath), "image-cache");
151
- return {
152
- profileName: "plexus-home-image-cache",
153
- stateRoot,
154
- launcherImage: joinPathLike(stateRoot, "launcher", "PharoLauncher.image"),
155
- imagesDir: joinPathLike(stateRoot, "images"),
156
- // The default profile's VMs: a store of its own aged apart, and its old
157
- // VM stopped running on a newer macOS while the default one ran. One VM
158
- // per Pharo version is one to renew, and the cache builds on the VM its
159
- // copies then run on.
160
- vmsDir: joinPathLike(homeProfilesRoot(homePath), "vms"),
161
- templateSourcesDir: joinPathLike(stateRoot, "templates"),
162
- initScriptsDir: joinPathLike(stateRoot, "init-scripts"),
163
- logsDir: joinPathLike(stateRoot, "logs"),
164
- launcherConfiguration: joinPathLike(stateRoot, "launcher", "pharo-launcher-cli-config.ston"),
165
- };
166
- }
167
- export function profileEnvironmentFromPaths(paths) {
168
- return {
169
- PHARO_LAUNCHER_MCP_PROFILE: paths.profileName,
170
- PHARO_LAUNCHER_MCP_STATE_ROOT: paths.stateRoot,
171
- PHARO_LAUNCHER_MCP_LAUNCHER_IMAGE: paths.launcherImage,
172
- PHARO_LAUNCHER_MCP_IMAGES_DIR: paths.imagesDir,
173
- PHARO_LAUNCHER_MCP_VMS_DIR: paths.vmsDir,
174
- PHARO_LAUNCHER_MCP_TEMPLATE_SOURCES_DIR: paths.templateSourcesDir,
175
- PHARO_LAUNCHER_MCP_INIT_SCRIPTS_DIR: paths.initScriptsDir,
176
- PHARO_LAUNCHER_MCP_LOGS_DIR: paths.logsDir,
177
- PHARO_LAUNCHER_MCP_LAUNCHER_CONFIGURATION: paths.launcherConfiguration,
178
- };
179
- }
180
- export function profilePathsFromEnvironment(environment) {
181
- if (!environment) {
182
- return undefined;
183
- }
184
- const requiredKeys = [
185
- "PHARO_LAUNCHER_MCP_PROFILE",
186
- "PHARO_LAUNCHER_MCP_STATE_ROOT",
187
- "PHARO_LAUNCHER_MCP_LAUNCHER_IMAGE",
188
- "PHARO_LAUNCHER_MCP_IMAGES_DIR",
189
- "PHARO_LAUNCHER_MCP_VMS_DIR",
190
- "PHARO_LAUNCHER_MCP_TEMPLATE_SOURCES_DIR",
191
- "PHARO_LAUNCHER_MCP_INIT_SCRIPTS_DIR",
192
- "PHARO_LAUNCHER_MCP_LOGS_DIR",
193
- "PHARO_LAUNCHER_MCP_LAUNCHER_CONFIGURATION",
194
- ];
195
- if (requiredKeys.some((key) => !environment[key])) {
196
- return undefined;
197
- }
198
- return {
199
- profileName: environment.PHARO_LAUNCHER_MCP_PROFILE,
200
- stateRoot: environment.PHARO_LAUNCHER_MCP_STATE_ROOT,
201
- launcherImage: environment.PHARO_LAUNCHER_MCP_LAUNCHER_IMAGE,
202
- imagesDir: environment.PHARO_LAUNCHER_MCP_IMAGES_DIR,
203
- vmsDir: environment.PHARO_LAUNCHER_MCP_VMS_DIR,
204
- templateSourcesDir: environment.PHARO_LAUNCHER_MCP_TEMPLATE_SOURCES_DIR,
205
- initScriptsDir: environment.PHARO_LAUNCHER_MCP_INIT_SCRIPTS_DIR,
206
- logsDir: environment.PHARO_LAUNCHER_MCP_LOGS_DIR,
207
- launcherConfiguration: environment.PHARO_LAUNCHER_MCP_LAUNCHER_CONFIGURATION,
208
- };
209
- }
210
- export function inferPharoMajorVersionFromTemplateText(value) {
211
- if (!value) {
212
- return undefined;
213
- }
214
- const namedMatch = /\b(?:Pharo|Moose)\s*(\d{1,2})(?:\.\d+)?\b/i.exec(value);
215
- if (namedMatch) {
216
- return Number.parseInt(namedMatch[1], 10);
217
- }
218
- const numericMatch = /^(\d{1,2})(?:\.\d+)?$/.exec(value.trim());
219
- if (numericMatch) {
220
- return Number.parseInt(numericMatch[1], 10);
221
- }
222
- const launcherVersionMatch = /^(\d{2})0$/.exec(value.trim());
223
- if (launcherVersionMatch) {
224
- return Number.parseInt(launcherVersionMatch[1], 10);
225
- }
226
- return undefined;
227
- }
228
- export function classifyHomeImageCachePharoMcpSupport(options) {
229
- const policy = resolveProjectRuntimePolicy(options.config).pharoMcp;
230
- const majorVersion = inferPharoMajorVersionFromTemplateText(options.templateMetadata?.pharoVersion) ?? inferPharoMajorVersionFromTemplateText(options.source.templateName);
231
- if (majorVersion === undefined) {
232
- return {
233
- status: "unknown",
234
- metadataKey: policy.metadataKey,
235
- supportedMajorVersions: [...policy.supportedMajorVersions],
236
- reason: "PLexus could not infer the Pharo major version from launcher template metadata.",
237
- };
238
- }
239
- const supported = policy.supportedMajorVersions.includes(majorVersion);
240
- return {
241
- status: supported ? "supported" : "unsupported",
242
- metadataKey: policy.metadataKey,
243
- actualMajorVersion: majorVersion,
244
- supportedMajorVersions: [...policy.supportedMajorVersions],
245
- reason: supported
246
- ? `Pharo ${majorVersion} is supported for Pharo MCP preparation.`
247
- : `Pharo ${majorVersion} is not supported for Pharo MCP preparation.`,
248
- };
249
- }
250
- export function homeImageCacheKeyMaterial(options) {
251
- const support = classifyHomeImageCachePharoMcpSupport({
252
- config: options.config,
253
- source: options.source,
254
- templateMetadata: options.templateMetadata,
255
- });
256
- const startupMode = projectMcpStartupMode(options.mcp);
257
- const load = startupMode !== "disabled" && support.status === "supported"
258
- ? pharoMcpLoad(options.projectRoot, options.mcp)
259
- : undefined;
260
- return {
261
- schemaVersion: homeImageCacheSchemaVersion,
262
- projectCachePolicy: {
263
- pharoMcpPreparation: startupMode === "disabled" ? "disabled" : "load-when-supported",
264
- pharoMcpStartupMode: startupMode,
265
- },
266
- source: options.source,
267
- ...(options.templateMetadata ? { templateMetadata: options.templateMetadata } : {}),
268
- pharoMcp: {
269
- support,
270
- ...(load ? { load } : {}),
271
- },
272
- ...(options.git ? { git: { transport: options.git.transport } } : {}),
273
- };
274
- }
275
- /** Decided the way `preparationScriptSource` decides it. */
276
- function pharoMcpLoad(projectRoot, mcp) {
277
- if (projectRoot !== undefined || isAbsolutePathLike(mcp.loadScript)) {
278
- const loadScriptPath = resolveMcpLoadScriptPath(projectRoot ?? "", mcp);
279
- if (fs.existsSync(loadScriptPath)) {
280
- return {
281
- kind: "loadScript",
282
- sha256: sha256Hex(fs.readFileSync(loadScriptPath, "utf8")),
283
- };
284
- }
285
- }
286
- return {
287
- kind: "metacello",
288
- repository: toMetacelloRepository("repository" in mcp ? mcp.repository : undefined),
289
- };
290
- }
291
- export function deriveHomeImageCacheKey(material) {
292
- return sha256Hex(stableJson(material));
293
- }
294
- export function readHomeImageCacheManifest(manifestPath) {
295
- if (!fs.existsSync(manifestPath)) {
296
- return { status: "missing", manifestPath };
297
- }
298
- try {
299
- return {
300
- status: "ok",
301
- manifestPath,
302
- manifest: JSON.parse(fs.readFileSync(manifestPath, "utf8")),
303
- };
304
- }
305
- catch (error) {
306
- return {
307
- status: "corrupt",
308
- manifestPath,
309
- error: error instanceof Error ? error.message : String(error),
310
- };
311
- }
312
- }
313
- export function writeHomeImageCacheManifest(manifest) {
314
- fs.mkdirSync(dirnamePathLike(manifest.paths.manifestPath), { recursive: true });
315
- const temporaryPath = `${manifest.paths.manifestPath}.tmp-${process.pid}`;
316
- fs.writeFileSync(temporaryPath, `${JSON.stringify(manifest, null, 2)}\n`, "utf8");
317
- fs.renameSync(temporaryPath, manifest.paths.manifestPath);
318
- }
319
- export function readHomeImageCacheLock(lockPath) {
320
- const lockFile = joinPathLike(lockPath, "lock.json");
321
- if (!fs.existsSync(lockFile)) {
322
- if (fs.existsSync(lockPath)) {
323
- return {
324
- status: "corrupt",
325
- lockPath,
326
- error: "Lock directory exists without lock.json",
327
- };
328
- }
329
- return { status: "missing", lockPath };
330
- }
331
- try {
332
- return {
333
- status: "ok",
334
- lockPath,
335
- lock: JSON.parse(fs.readFileSync(lockFile, "utf8")),
336
- };
337
- }
338
- catch (error) {
339
- return {
340
- status: "corrupt",
341
- lockPath,
342
- error: error instanceof Error ? error.message : String(error),
343
- };
344
- }
345
- }
346
- export function tryAcquireHomeImageCacheLock(options) {
347
- fs.mkdirSync(dirnamePathLike(options.lockPath), { recursive: true });
348
- try {
349
- fs.mkdirSync(options.lockPath, { recursive: false });
350
- }
351
- catch {
352
- return {
353
- acquired: false,
354
- current: readHomeImageCacheLock(options.lockPath),
355
- };
356
- }
357
- const lock = {
358
- key: options.key,
359
- owner: options.owner,
360
- acquiredAt: (options.now ?? (() => new Date()))().toISOString(),
361
- };
362
- fs.writeFileSync(joinPathLike(options.lockPath, "lock.json"), `${JSON.stringify(lock, null, 2)}\n`, "utf8");
363
- return { acquired: true, lock };
364
- }
365
- export function releaseHomeImageCacheLock(lockPath) {
366
- fs.rmSync(lockPath, { recursive: true, force: true });
367
- }
368
- export function listHomeImageCacheManifests(cacheRoot) {
369
- const entriesRoot = joinPathLike(cacheRoot, "entries");
370
- if (!fs.existsSync(entriesRoot)) {
371
- return [];
372
- }
373
- return fs
374
- .readdirSync(entriesRoot, { withFileTypes: true })
375
- .filter((entry) => entry.isDirectory())
376
- .map((entry) => readHomeImageCacheManifest(joinPathLike(entriesRoot, entry.name, "manifest.json")));
377
- }
378
- export function planHomeImageCacheFlush(options) {
379
- const homePath = resolvePlexusHomePath(options);
380
- const cacheRoot = homeImageCacheRootPath(homePath);
381
- const keys = options.key
382
- ? [safeCacheKey(options.key)]
383
- : fs.existsSync(joinPathLike(cacheRoot, "entries"))
384
- ? fs
385
- .readdirSync(joinPathLike(cacheRoot, "entries"), {
386
- withFileTypes: true,
387
- })
388
- .filter((entry) => entry.isDirectory())
389
- .map((entry) => entry.name)
390
- : [];
391
- return {
392
- homePath,
393
- cacheRoot,
394
- ...(options.key ? { key: options.key } : {}),
395
- entries: keys.map((key) => {
396
- const entryDirectory = homeImageCacheEntryDirectory(cacheRoot, key);
397
- return {
398
- key,
399
- entryDirectory,
400
- manifestPath: homeImageCacheManifestPath(cacheRoot, key),
401
- lockPath: homeImageCacheLockPath(cacheRoot, key),
402
- exists: fs.existsSync(entryDirectory),
403
- };
404
- }),
405
- };
406
- }
407
- export function flushHomeImageCache(plan) {
408
- for (const entry of plan.entries) {
409
- fs.rmSync(entry.entryDirectory, { recursive: true, force: true });
410
- fs.rmSync(entry.lockPath, { recursive: true, force: true });
411
- }
412
- }
413
- function manifestPreparationStatus(support, mcp) {
414
- return support.status === "supported" &&
415
- projectMcpStartupMode(mcp) !== "disabled"
416
- ? "pending"
417
- : "skipped";
418
- }
419
- function planStatus(enabled, manifest, lock, cachedImageExists) {
420
- if (!enabled) {
421
- return "disabled";
422
- }
423
- if (manifest.status === "ok") {
424
- if (manifest.manifest.pharoMcp.preparationStatus === "failed") {
425
- return "corrupt";
426
- }
427
- // A manifest is a claim about an image, and the image is what gets copied.
428
- // The two live in different roots: the entry stays under the cache root
429
- // while the image sits in the cache profile, so moving the profile leaves
430
- // every manifest written before the move pointing at nothing. Believing
431
- // the claim turns a cache that should prepare again into a copy from a
432
- // directory that is not there.
433
- return cachedImageExists ? "hit" : "corrupt";
434
- }
435
- if (manifest.status === "corrupt") {
436
- return "corrupt";
437
- }
438
- return lock.status === "ok" || lock.status === "corrupt"
439
- ? "in-progress"
440
- : "miss";
441
- }
442
- function resolvedLocalInputAvailability(options) {
443
- return options.inputs?.[options.key] ?? options.inferred ?? "unknown";
444
- }
445
- function localOnlyReadiness(options) {
446
- if (options.networkPolicy !== "local-only") {
447
- return {
448
- status: "not-required",
449
- missingInputs: [],
450
- diagnostics: [],
451
- };
452
- }
453
- if (options.status === "hit") {
454
- return {
455
- status: "ready",
456
- missingInputs: [],
457
- diagnostics: [],
458
- };
459
- }
460
- if (options.status !== "miss" && options.status !== "corrupt") {
461
- return {
462
- status: "not-required",
463
- missingInputs: [],
464
- diagnostics: [],
465
- };
466
- }
467
- const diagnostics = [...(options.localInputs?.diagnostics ?? [])];
468
- const missingInputs = [];
469
- const requireInput = (key, label, inferred) => {
470
- const availability = resolvedLocalInputAvailability({
471
- key,
472
- inputs: options.localInputs,
473
- inferred,
474
- });
475
- if (availability === "available") {
476
- return;
477
- }
478
- missingInputs.push(key);
479
- diagnostics.push(availability === "missing"
480
- ? `${label} is missing for local-only home image cache preparation.`
481
- : `${label} has not been proven local for local-only home image cache preparation.`);
482
- };
483
- const loadScriptPath = resolveMcpLoadScriptPath(options.projectRoot, options.mcp);
484
- const startupMode = projectMcpStartupMode(options.mcp);
485
- requireInput("templateSource", "The selected home launcher template source", options.templateMetadata?.sourceFile ? "available" : undefined);
486
- requireInput("baseImage", "The selected Pharo base image artifact");
487
- requireInput("vm", "The selected Pharo VM");
488
- if (options.support.status === "supported" && startupMode !== "disabled") {
489
- requireInput("pharoMcpLoadScript", "The Pharo MCP load script", fs.existsSync(loadScriptPath) ? "available" : "missing");
490
- requireInput("pharoMcpDependencies", "The Pharo MCP load script dependencies");
491
- }
492
- if (missingInputs.length === 0) {
493
- diagnostics.push("PLexus home image cache is in local-only mode; template catalog refresh will be skipped.");
494
- return {
495
- status: "ready",
496
- missingInputs,
497
- diagnostics,
498
- };
499
- }
500
- return {
501
- status: "missing",
502
- missingInputs,
503
- diagnostics,
504
- };
505
- }
506
- function preparationScriptSource(options) {
507
- const repository = toMetacelloRepository("repository" in options.mcp ? options.mcp.repository : undefined);
508
- const loadScriptPath = resolveMcpLoadScriptPath(options.projectRoot, options.mcp);
509
- const quoted = (value) => `'${value.replaceAll("'", "''")}'`;
510
- const pathString = (value) => quoted(value.replace(/\\/g, "/"));
511
- const repositoryLabel = pharoMcpMetacelloRepositoryLocation(repository);
512
- return `"Generated by PLexus. Do not edit."
513
-
514
- | loadScript preparationStatusFile preparationStatusWriter preparationSource |
515
-
516
- Smalltalk globals at: #PLexusHomeImageCacheKey put: ${quoted(options.cacheId)}.
517
-
518
- preparationStatusFile := ${pathString(options.statusPath)} asFileReference.
519
- preparationStatusFile exists ifTrue: [ preparationStatusFile delete ].
520
- preparationSource := 'pending'.
521
- preparationStatusWriter := [ :status :message |
522
- preparationStatusFile parent ensureCreateDirectory.
523
- preparationStatusFile writeStreamDo: [ :stream |
524
- stream nextPutAll: 'status='; nextPutAll: status; cr.
525
- stream nextPutAll: 'cacheKey='; nextPutAll: ${quoted(options.cacheId)}; cr.
526
- stream
527
- nextPutAll: 'source=';
528
- nextPutAll: (preparationSource ifNil: [ 'unknown' ]);
529
- cr.
530
- stream nextPutAll: 'loadScript='; nextPutAll: ${pathString(loadScriptPath)}; cr.
531
- stream nextPutAll: 'repository='; nextPutAll: ${quoted(repositoryLabel)}; cr.
532
- stream nextPutAll: 'baseline='; nextPutAll: ${quoted(repository.baseline)}; cr.
533
- message ifNotNil: [
534
- stream nextPutAll: 'message='; nextPutAll: message asString; cr ] ] ].
535
- [
536
- loadScript := ${pathString(loadScriptPath)} asFileReference.
537
- loadScript exists
538
- ifTrue: [
539
- preparationSource := 'loadScript'.
540
- loadScript fileIn ]
541
- ifFalse: [
542
- preparationSource := 'metacello'.
543
- Metacello new
544
- githubUser: ${quoted(repository.githubUser)} project: ${quoted(repository.project)} commitish: ${quoted(repository.commitish)} path: ${quoted(repository.path)};
545
- baseline: ${quoted(repository.baseline)};
546
- load ].
547
-
548
- (Smalltalk globals includesKey: #MCP)
549
- ifFalse: [ Error signal: 'MCP class is not available after home image cache preparation.' ].
550
- preparationStatusWriter value: 'loaded' value: nil
551
- ] on: Error do: [ :error |
552
- preparationStatusWriter value: 'failed' value: error description.
553
- error pass ].
554
-
555
- Smalltalk globals at: #PLexusHomeImageCachePreparedAt put: DateAndTime now asString.
556
- Smalltalk snapshot: true andQuit: true.
557
- `;
558
- }
559
- function buildHomeImageCacheDiagnostics(options) {
560
- const diagnostics = [];
561
- if (!options.enabled) {
562
- diagnostics.push("PLexus home image cache is disabled by project config.");
563
- }
564
- if (options.manifest.status === "corrupt") {
565
- diagnostics.push(`Home image cache manifest is unreadable: ${options.manifest.error}`);
566
- }
567
- if (options.lock.status === "ok") {
568
- diagnostics.push(`Home image cache entry is already being prepared by ${options.lock.lock.owner}.`);
569
- }
570
- if (options.lock.status === "corrupt") {
571
- diagnostics.push(`Home image cache lock is unreadable: ${options.lock.error}`);
572
- }
573
- if (options.imageState && !options.destinationProfile) {
574
- diagnostics.push("Runtime copy from the home image cache requires an explicit destination launcher profile.");
575
- }
576
- diagnostics.push(...options.offlineReadiness.diagnostics);
577
- return diagnostics;
578
- }
579
- function homeImageCacheCanPrepareEntry(options) {
580
- const shouldPrepare = options.status === "miss" || options.status === "corrupt";
581
- return (options.enabled &&
582
- shouldPrepare &&
583
- (options.networkPolicy === "online" ||
584
- options.offlineReadiness.status === "ready"));
585
- }
586
- function buildHomeImageCachePlanOperations(options) {
587
- const refreshTemplateCatalog = options.canPrepareCacheEntry && options.networkPolicy === "online"
588
- ? {
589
- toolName: "pharo_launcher_template_update",
590
- profileEnvironment: profileEnvironmentFromPaths(options.homeProfile),
591
- argumentsValue: {},
592
- requiresApproval: true,
593
- reason: "A fresh PLexus home image cache profile must have a launcher template catalog before creating a cache base.",
594
- }
595
- : undefined;
596
- // An attempt that failed after the launcher registered the cache base leaves
597
- // the name taken: the manifest says the entry is unusable, yet every rebuild
598
- // asks for the same name and the launcher refuses it. Drop the leftover base
599
- // first so a failed entry can be built again.
600
- const discardCacheImage = options.canPrepareCacheEntry &&
601
- fs.existsSync(joinPathLike(options.homeProfile.imagesDir, options.cacheImageName))
602
- ? {
603
- toolName: "pharo_launcher_image_delete",
604
- profileEnvironment: profileEnvironmentFromPaths(options.homeProfile),
605
- argumentsValue: {
606
- imageName: options.cacheImageName,
607
- force: true,
608
- },
609
- requiresApproval: true,
610
- reason: "A home image cache base left by a failed attempt must be removed before it is built again.",
611
- }
612
- : undefined;
613
- const createCacheImage = options.canPrepareCacheEntry
614
- ? {
615
- toolName: "pharo_launcher_image_create",
616
- profileEnvironment: profileEnvironmentFromPaths(options.homeProfile),
617
- argumentsValue: {
618
- newImageName: options.cacheImageName,
619
- templateName: options.source.templateName,
620
- ...(options.source.templateCategory
621
- ? { templateCategory: options.source.templateCategory }
622
- : {}),
623
- noLaunch: true,
624
- },
625
- requiresApproval: true,
626
- reason: "Creating a PLexus home image cache base mutates the explicit home launcher profile.",
627
- }
628
- : undefined;
629
- const prepareCacheImage = options.canPrepareCacheEntry &&
630
- options.keyMaterial.pharoMcp.support.status === "supported" &&
631
- projectMcpStartupMode(options.mcp) !== "disabled"
632
- ? {
633
- toolName: "pharo_launcher_image_start",
634
- profileEnvironment: profileEnvironmentFromPaths(options.homeProfile),
635
- argumentsValue: {
636
- imageName: options.cacheImageName,
637
- detached: false,
638
- displayMode: "headless",
639
- script: options.preparationScriptPath,
640
- // The VM's output, and the launcher's report of which VM it ran:
641
- // a VM that cannot run an image says there how to renew it.
642
- includeRaw: true,
643
- },
644
- requiresApproval: true,
645
- reason: "Preparing a supported Pharo MCP cache image must run headlessly, snapshot, and quit.",
646
- }
647
- : undefined;
648
- const runtimeCopy = options.enabled &&
649
- options.imageState &&
650
- options.destinationProfile &&
651
- (options.status === "hit" || options.canPrepareCacheEntry)
652
- ? {
653
- toolName: "pharo_launcher_image_copy_between_profiles",
654
- argumentsValue: {
655
- sourceProfile: options.homeProfile,
656
- destinationProfile: options.destinationProfile,
657
- sourceImageName: options.cacheImageName,
658
- destinationImageName: options.imageState.imageName,
659
- },
660
- requiresApproval: true,
661
- reason: "Runtime images must be copies of home cache bases and must stay in the project launcher profile.",
662
- }
663
- : undefined;
664
- return {
665
- ...(refreshTemplateCatalog ? { refreshTemplateCatalog } : {}),
666
- ...(discardCacheImage ? { discardCacheImage } : {}),
667
- ...(createCacheImage ? { createCacheImage } : {}),
668
- ...(prepareCacheImage ? { prepareCacheImage } : {}),
669
- ...(runtimeCopy ? { runtimeCopy } : {}),
670
- };
671
- }
672
- export function buildHomeImageCachePlan(options) {
673
- const { source, mcp } = sourceFromProjectImage(options.config, options.imageConfig);
674
- const homePath = resolvePlexusHomePath(options);
675
- const cacheRoot = homeImageCacheRootPath(homePath);
676
- const keyMaterial = homeImageCacheKeyMaterial({
677
- config: options.config,
678
- source,
679
- mcp,
680
- git: options.imageConfig.git,
681
- templateMetadata: options.templateMetadata,
682
- projectRoot: options.projectRoot,
683
- });
684
- const key = deriveHomeImageCacheKey(keyMaterial);
685
- const entryDirectory = homeImageCacheEntryDirectory(cacheRoot, key);
686
- const manifestPath = homeImageCacheManifestPath(cacheRoot, key);
687
- const lockPath = homeImageCacheLockPath(cacheRoot, key);
688
- const preparationScriptPath = homeImageCachePreparationScriptPath(cacheRoot, key);
689
- const preparationStatusPath = homeImageCachePreparationStatusPath(cacheRoot, key);
690
- const cacheImageName = homeImageCacheImageName(key);
691
- const homeProfile = homeImageCacheProfile(homePath);
692
- const manifest = readHomeImageCacheManifest(manifestPath);
693
- const lock = readHomeImageCacheLock(lockPath);
694
- const enabled = homeImageCacheEnabled(options.config);
695
- const networkPolicy = homeImageCacheNetworkPolicy(options.config);
696
- const status = planStatus(enabled, manifest, lock, imageFileExists(homeProfile.imagesDir, cacheImageName));
697
- const destinationProfile = profilePathsFromEnvironment(pharoLauncherMcpProfileEnvironment({
698
- projectRoot: options.projectRoot,
699
- config: options.config,
700
- workspaceId: options.workspaceId ?? "default",
701
- stateRoot: options.stateRoot,
702
- }));
703
- const offlineReadiness = localOnlyReadiness({
704
- networkPolicy,
705
- status,
706
- support: keyMaterial.pharoMcp.support,
707
- projectRoot: options.projectRoot,
708
- mcp,
709
- templateMetadata: options.templateMetadata,
710
- localInputs: options.localInputs,
711
- });
712
- const diagnostics = buildHomeImageCacheDiagnostics({
713
- enabled,
714
- manifest,
715
- lock,
716
- imageState: options.imageState,
717
- destinationProfile,
718
- offlineReadiness,
719
- });
720
- const now = options.now ?? (() => new Date());
721
- const expectedManifest = {
722
- schemaVersion: homeImageCacheSchemaVersion,
723
- key,
724
- createdAt: now().toISOString(),
725
- updatedAt: now().toISOString(),
726
- cacheImageName,
727
- source,
728
- ...(options.templateMetadata ? { templateMetadata: options.templateMetadata } : {}),
729
- pharoMcp: {
730
- support: keyMaterial.pharoMcp.support,
731
- preparationStatus: manifestPreparationStatus(keyMaterial.pharoMcp.support, mcp),
732
- diagnostics,
733
- },
734
- paths: {
735
- entryDirectory,
736
- manifestPath,
737
- lockPath,
738
- preparationScriptPath,
739
- preparationStatusPath,
740
- profileStateRoot: homeProfile.stateRoot,
741
- },
742
- };
743
- const canPrepareCacheEntry = homeImageCacheCanPrepareEntry({
744
- enabled,
745
- status,
746
- networkPolicy,
747
- offlineReadiness,
748
- });
749
- const operations = buildHomeImageCachePlanOperations({
750
- canPrepareCacheEntry,
751
- networkPolicy,
752
- homeProfile,
753
- source,
754
- cacheImageName,
755
- keyMaterial,
756
- mcp,
757
- preparationScriptPath,
758
- enabled,
759
- imageState: options.imageState,
760
- destinationProfile,
761
- status,
762
- });
763
- return {
764
- status,
765
- networkPolicy,
766
- offlineReadiness,
767
- key,
768
- projectRoot: options.projectRoot,
769
- homePath,
770
- cacheRoot,
771
- entryDirectory,
772
- manifestPath,
773
- lockPath,
774
- cacheImageName,
775
- source,
776
- mcp,
777
- support: keyMaterial.pharoMcp.support,
778
- manifest,
779
- lock,
780
- homeProfile,
781
- keyMaterial,
782
- expectedManifest,
783
- ...operations,
784
- diagnostics,
785
- };
786
- }
787
- export function writeHomeImageCachePreparationScript(plan) {
788
- const source = preparationScriptSource({
789
- cacheId: plan.key,
790
- projectRoot: plan.projectRoot,
791
- source: plan.source,
792
- mcp: plan.mcp,
793
- statusPath: plan.expectedManifest.paths.preparationStatusPath,
794
- });
795
- fs.mkdirSync(dirnamePathLike(plan.expectedManifest.paths.preparationScriptPath), {
796
- recursive: true,
797
- });
798
- fs.writeFileSync(plan.expectedManifest.paths.preparationScriptPath, source, "utf8");
799
- return {
800
- filePath: plan.expectedManifest.paths.preparationScriptPath,
801
- source,
802
- };
803
- }
804
- function assertLauncherOk(result, toolName) {
805
- if (result && result.ok === false) {
806
- throw new HomeImageCacheError(`${toolName} returned ok: false`);
807
- }
808
- }
809
- function requireMutationApproval(approval, operation) {
810
- if (!approval?.approved || approval.approvalId.length === 0) {
811
- throw new HomeImageCacheError(`${operation} requires approved home image cache mutation`);
812
- }
813
- return approval;
814
- }
815
- async function callLauncherOperation(client, operation) {
816
- const result = await client.callTool(operation.toolName, operation.argumentsValue);
817
- assertLauncherOk(result, operation.toolName);
818
- }
819
- function finalizedManifest(options) {
820
- const timestamp = (options.now ?? (() => new Date()))().toISOString();
821
- const existingCreatedAt = options.plan.manifest.status === "ok"
822
- ? options.plan.manifest.manifest.createdAt
823
- : undefined;
824
- return {
825
- ...options.plan.expectedManifest,
826
- createdAt: existingCreatedAt ?? timestamp,
827
- updatedAt: timestamp,
828
- pharoMcp: {
829
- ...options.plan.expectedManifest.pharoMcp,
830
- preparationStatus: options.preparationStatus,
831
- diagnostics: [
832
- ...options.plan.diagnostics,
833
- ...(options.diagnostics ?? []),
834
- ],
835
- },
836
- };
837
- }
838
- function preparationStatusProperties(filePath) {
839
- if (!fs.existsSync(filePath)) {
840
- return undefined;
841
- }
842
- return Object.fromEntries(fs
843
- .readFileSync(filePath, "utf8")
844
- .split(/\r\n|\n|\r/)
845
- .map((line) => {
846
- if (!line || line.startsWith("#")) {
847
- return undefined;
848
- }
849
- const separator = line.indexOf("=");
850
- if (separator <= 0) {
851
- return undefined;
852
- }
853
- return [line.slice(0, separator), line.slice(separator + 1)];
854
- })
855
- .filter((entry) => entry !== undefined));
856
- }
857
- function preparationFailureDiagnostic(plan) {
858
- const properties = preparationStatusProperties(plan.expectedManifest.paths.preparationStatusPath);
859
- if (properties?.status !== "failed") {
860
- return undefined;
861
- }
862
- const message = properties.message ??
863
- "Pharo MCP preparation failed without a reported message.";
864
- return `Home image cache Pharo MCP preparation failed: ${message}`;
865
- }
866
- async function prepareHomeImageCacheEntry(options) {
867
- if (!options.plan.createCacheImage) {
868
- return [];
869
- }
870
- const lock = tryAcquireHomeImageCacheLock({
871
- lockPath: options.plan.lockPath,
872
- key: options.plan.key,
873
- owner: options.approval.approvalId,
874
- now: options.now,
875
- });
876
- if (!lock.acquired) {
877
- const detail = lock.current.status === "ok"
878
- ? `current owner: ${lock.current.lock.owner}`
879
- : lock.current.status === "corrupt"
880
- ? lock.current.error
881
- : "lock appeared before acquisition";
882
- throw new HomeImageCacheError(`Home image cache entry ${options.plan.key} is already being prepared (${detail})`);
883
- }
884
- const operations = [];
885
- try {
886
- if (options.plan.prepareCacheImage) {
887
- fs.rmSync(options.plan.expectedManifest.paths.preparationStatusPath, {
888
- force: true,
889
- });
890
- writeHomeImageCachePreparationScript(options.plan);
891
- }
892
- if (options.plan.refreshTemplateCatalog) {
893
- // The cache keeps a launcher profile of its own, and its sources list is
894
- // seeded once. Refresh that list before the launcher reads it, or a seed
895
- // from an earlier Pharo cycle keeps naming templates that no longer exist.
896
- await prepareScopedTemplateCatalog({
897
- destinationDirectory: options.plan.homeProfile.templateSourcesDir,
898
- networkPolicy: options.plan.networkPolicy,
899
- fetch: options.fetch,
900
- });
901
- await callLauncherOperation(options.homeClient, options.plan.refreshTemplateCatalog);
902
- operations.push(options.plan.refreshTemplateCatalog);
903
- }
904
- if (options.plan.discardCacheImage) {
905
- await callLauncherOperation(options.homeClient, options.plan.discardCacheImage);
906
- operations.push(options.plan.discardCacheImage);
907
- // The launcher only drops the image files it knows about. Whatever else
908
- // the template installed beside them stays, and the next create fails
909
- // copying onto it, so take the cache base directory with it.
910
- fs.rmSync(joinPathLike(options.plan.homeProfile.imagesDir, options.plan.cacheImageName), { recursive: true, force: true });
911
- }
912
- await callLauncherOperation(options.homeClient, options.plan.createCacheImage);
913
- operations.push(options.plan.createCacheImage);
914
- if (options.plan.prepareCacheImage) {
915
- await callLauncherOperation(options.homeClient, options.plan.prepareCacheImage);
916
- operations.push(options.plan.prepareCacheImage);
917
- }
918
- writeHomeImageCacheManifest(finalizedManifest({
919
- plan: options.plan,
920
- preparationStatus: options.plan.prepareCacheImage ? "prepared" : "skipped",
921
- now: options.now,
922
- }));
923
- return operations;
924
- }
925
- catch (error) {
926
- writeHomeImageCacheManifest(finalizedManifest({
927
- plan: options.plan,
928
- preparationStatus: "failed",
929
- diagnostics: [
930
- preparationFailureDiagnostic(options.plan) ??
931
- (error instanceof Error ? error.message : String(error)),
932
- ],
933
- now: options.now,
934
- }));
935
- throw error;
936
- }
937
- finally {
938
- releaseHomeImageCacheLock(options.plan.lockPath);
939
- }
940
- }
941
- function ensureMaterializableHomeImageCachePlan(plan) {
942
- if (plan.status === "disabled") {
943
- return false;
944
- }
945
- if (plan.offlineReadiness.status === "missing") {
946
- throw new HomeImageCacheError([
947
- `Home image cache local-only preparation is missing required local inputs for entry ${plan.key}: ${plan.offlineReadiness.missingInputs.join(", ")}`,
948
- ...plan.offlineReadiness.diagnostics,
949
- ].join("\n"));
950
- }
951
- if (plan.status === "in-progress") {
952
- const detail = plan.lock.status === "ok"
953
- ? `current owner: ${plan.lock.lock.owner}`
954
- : plan.lock.status === "corrupt"
955
- ? plan.lock.error
956
- : "lock is present";
957
- throw new HomeImageCacheError(`Home image cache entry ${plan.key} is already being prepared (${detail})`);
958
- }
959
- return true;
960
- }
961
- function materializationNeedsHomeClient(plan) {
962
- return plan.status === "miss" || plan.status === "corrupt";
963
- }
964
- async function runHomeCacheMaterializationOperations(options) {
965
- const operations = [];
966
- if (materializationNeedsHomeClient(options.plan)) {
967
- if (!options.homeClient) {
968
- throw new HomeImageCacheError("Home image cache preparation requires a home launcher client");
969
- }
970
- operations.push(...(await prepareHomeImageCacheEntry({
971
- plan: options.plan,
972
- homeClient: options.homeClient,
973
- approval: options.approval,
974
- fetch: options.fetch,
975
- now: options.now,
976
- })));
977
- }
978
- if (options.plan.runtimeCopy) {
979
- await callLauncherOperation(options.runtimeClient, options.plan.runtimeCopy);
980
- operations.push(options.plan.runtimeCopy);
981
- }
982
- return operations;
983
- }
984
- export async function materializeProjectImageFromHomeCache(options) {
985
- if (!projectImageCanUseHomeImageCache(options.imageConfig)) {
986
- return undefined;
987
- }
988
- const plan = buildHomeImageCachePlan({
989
- projectRoot: options.projectRoot,
990
- config: options.config,
991
- imageConfig: options.imageConfig,
992
- imageState: options.imageState,
993
- workspaceId: options.workspaceId,
994
- stateRoot: options.stateRoot,
995
- env: options.env,
996
- homeDirectory: options.homeDirectory,
997
- now: options.now,
998
- templateMetadata: options.templateMetadata,
999
- localInputs: options.localInputs,
1000
- });
1001
- if (!ensureMaterializableHomeImageCachePlan(plan)) {
1002
- return undefined;
1003
- }
1004
- const approval = requireMutationApproval(options.approval, `Materializing image ${options.imageState.id} from the home image cache`);
1005
- const operations = [];
1006
- let homeClient = options.homeClient;
1007
- let ownsHomeClient = false;
1008
- try {
1009
- if (materializationNeedsHomeClient(plan) && !homeClient) {
1010
- homeClient = openPharoLauncherClient({
1011
- profileEnvironment: profileEnvironmentFromPaths(plan.homeProfile),
1012
- });
1013
- ownsHomeClient = true;
1014
- }
1015
- operations.push(...(await runHomeCacheMaterializationOperations({
1016
- plan,
1017
- approval,
1018
- fetch: options.fetch,
1019
- now: options.now,
1020
- runtimeClient: options.runtimeClient,
1021
- homeClient,
1022
- })));
1023
- return { plan, operations };
1024
- }
1025
- finally {
1026
- if (ownsHomeClient) {
1027
- await homeClient?.close?.();
1028
- }
1029
- }
1030
- }
1031
- //# sourceMappingURL=homeImageCache.js.map