@evref-bl/pharo-launcher-mcp 0.1.1 → 0.1.3

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 (47) hide show
  1. package/README.md +158 -123
  2. package/bin/pharo-launcher.cmd +46 -46
  3. package/bin/pharo-launcher.sh +0 -0
  4. package/dist/commandCatalog.d.ts.map +1 -1
  5. package/dist/commandCatalog.js +17 -0
  6. package/dist/commandCatalog.js.map +1 -1
  7. package/dist/config.d.ts +21 -1
  8. package/dist/config.d.ts.map +1 -1
  9. package/dist/config.js +97 -11
  10. package/dist/config.js.map +1 -1
  11. package/dist/crossProfileCopy.d.ts +87 -0
  12. package/dist/crossProfileCopy.d.ts.map +1 -0
  13. package/dist/crossProfileCopy.js +437 -0
  14. package/dist/crossProfileCopy.js.map +1 -0
  15. package/dist/discovery.d.ts +165 -1
  16. package/dist/discovery.d.ts.map +1 -1
  17. package/dist/discovery.js +744 -1
  18. package/dist/discovery.js.map +1 -1
  19. package/dist/imageMetadata.d.ts +9 -0
  20. package/dist/imageMetadata.d.ts.map +1 -0
  21. package/dist/imageMetadata.js +82 -0
  22. package/dist/imageMetadata.js.map +1 -0
  23. package/dist/launcherCli.d.ts +7 -1
  24. package/dist/launcherCli.d.ts.map +1 -1
  25. package/dist/launcherCli.js +651 -32
  26. package/dist/launcherCli.js.map +1 -1
  27. package/dist/models.d.ts +2 -0
  28. package/dist/models.d.ts.map +1 -1
  29. package/dist/platform.d.ts +2 -0
  30. package/dist/platform.d.ts.map +1 -1
  31. package/dist/platform.js +21 -0
  32. package/dist/platform.js.map +1 -1
  33. package/dist/resultNormalizer.d.ts.map +1 -1
  34. package/dist/resultNormalizer.js +87 -1
  35. package/dist/resultNormalizer.js.map +1 -1
  36. package/dist/server.d.ts +6 -1
  37. package/dist/server.d.ts.map +1 -1
  38. package/dist/server.js +516 -6
  39. package/dist/server.js.map +1 -1
  40. package/docs/README.md +26 -0
  41. package/docs/cleanup-hook-boundary.md +94 -0
  42. package/docs/development.md +64 -22
  43. package/docs/reference/tools.md +179 -0
  44. package/docs/troubleshooting.md +135 -0
  45. package/docs/user/getting-started.md +172 -0
  46. package/docs/user/profile-mode.md +176 -0
  47. package/package.json +11 -6
@@ -1,7 +1,133 @@
1
1
  import { spawn } from "node:child_process";
2
+ import fs from "node:fs";
3
+ import path from "node:path";
2
4
  import { loadPharoLauncherConfig, } from "./config.js";
3
5
  import { resolveLauncherScript } from "./launcherScript.js";
6
+ import { parseLauncherOutput } from "./parser.js";
4
7
  import { shouldRunScriptThroughBash, shouldRunScriptThroughCommandShell, } from "./platform.js";
8
+ const POSIX_BASH_PATH_CANDIDATES = ["/bin/bash", "/usr/bin/bash"];
9
+ function comparablePath(value) {
10
+ const resolved = path.resolve(value);
11
+ return process.platform === "win32" ? resolved.toLowerCase() : resolved;
12
+ }
13
+ function isPathInside(parent, candidate) {
14
+ const normalizedParent = comparablePath(parent);
15
+ const normalizedCandidate = comparablePath(candidate);
16
+ const relative = path.relative(normalizedParent, normalizedCandidate);
17
+ return (relative === "" ||
18
+ (!!relative && !relative.startsWith("..") && !path.isAbsolute(relative)));
19
+ }
20
+ function stonFilePath(filePath) {
21
+ const normalized = path.resolve(filePath).replaceAll("\\", "/");
22
+ const stonPath = /^[A-Za-z]:\//.test(normalized)
23
+ ? `/${normalized}`
24
+ : normalized;
25
+ return stonPath.replaceAll("'", "''");
26
+ }
27
+ function safeFileSegment(value) {
28
+ const cleaned = value.replaceAll(/[^A-Za-z0-9._-]+/g, "-");
29
+ return cleaned.length > 0 ? cleaned : "image";
30
+ }
31
+ function detachedLaunchLogPaths(config, args, startTime) {
32
+ const logsDir = config.profile?.logsDir ?? path.join(process.cwd(), ".pharo-launcher-mcp", "logs");
33
+ const imageName = safeFileSegment(args.at(-1) ?? "image");
34
+ const stamp = new Date(startTime).toISOString().replaceAll(/[:.]/g, "-");
35
+ const baseName = `${stamp}-${imageName}-launch`;
36
+ return {
37
+ stdoutPath: path.join(logsDir, `${baseName}.out.log`),
38
+ stderrPath: path.join(logsDir, `${baseName}.err.log`),
39
+ };
40
+ }
41
+ function launcherEnvironment(config) {
42
+ return {
43
+ ...process.env,
44
+ PHARO_LAUNCHER_IMAGE: config.launcherImage,
45
+ PHARO_LAUNCHER_VM: config.launcherVm,
46
+ ...(config.profile
47
+ ? {
48
+ PHARO_LAUNCHER_MCP_PROFILE: config.profile.name,
49
+ PHARO_LAUNCHER_MCP_STATE_ROOT: config.profile.stateRoot,
50
+ PHARO_LAUNCHER_MCP_IMAGES_DIR: config.profile.imagesDir,
51
+ PHARO_LAUNCHER_MCP_VMS_DIR: config.profile.vmsDir,
52
+ PHARO_LAUNCHER_MCP_TEMPLATE_SOURCES_DIR: config.profile.templateSourcesDir,
53
+ PHARO_LAUNCHER_MCP_INIT_SCRIPTS_DIR: config.profile.initScriptsDir,
54
+ PHARO_LAUNCHER_MCP_LOGS_DIR: config.profile.logsDir,
55
+ }
56
+ : {}),
57
+ };
58
+ }
59
+ export function profileLauncherConfigurationContent(profile) {
60
+ return [
61
+ "PharoLauncherCLIConfiguration {",
62
+ `\t#imagesDirectory : FILE [ '${stonFilePath(profile.imagesDir)}' ],`,
63
+ `\t#vmsDirectory : FILE [ '${stonFilePath(profile.vmsDir)}' ],`,
64
+ "\t#launchImageFromALoginShell : true,",
65
+ `\t#initScriptsDirectory : FILE [ '${stonFilePath(profile.initScriptsDir)}' ],`,
66
+ `\t#templateSourcesFileLocation : FILE [ '${stonFilePath(profile.templateSourcesDir)}' ]`,
67
+ "}",
68
+ "",
69
+ ].join("\n");
70
+ }
71
+ function changesPathForImage(imagePath) {
72
+ return /\.image$/i.test(imagePath)
73
+ ? imagePath.replace(/\.image$/i, ".changes")
74
+ : `${imagePath}.changes`;
75
+ }
76
+ function copyIfExists(source, destination) {
77
+ if (fs.existsSync(source) && !fs.existsSync(destination)) {
78
+ fs.copyFileSync(source, destination);
79
+ }
80
+ }
81
+ function ensureProfileLauncherImage(config, profileLauncherImage) {
82
+ const installationLauncherImage = path.resolve(config.installationLauncherImage);
83
+ if (!fs.existsSync(profileLauncherImage)) {
84
+ if (!fs.existsSync(installationLauncherImage)) {
85
+ throw new Error([
86
+ "Cannot bootstrap profile launcher image because the installation PharoLauncher image is missing.",
87
+ `source: ${installationLauncherImage}`,
88
+ `destination: ${profileLauncherImage}`,
89
+ ].join("\n"));
90
+ }
91
+ fs.copyFileSync(installationLauncherImage, profileLauncherImage);
92
+ }
93
+ copyIfExists(changesPathForImage(installationLauncherImage), changesPathForImage(profileLauncherImage));
94
+ }
95
+ export function ensureProfileLauncherConfiguration(config) {
96
+ if (!config.profile) {
97
+ return;
98
+ }
99
+ const stateRoot = path.resolve(config.profile.stateRoot);
100
+ const profileLauncherImage = path.resolve(config.profile.launcherImage);
101
+ if (!isPathInside(stateRoot, profileLauncherImage)) {
102
+ throw new Error(`Refusing launcher profile image outside PHARO_LAUNCHER_MCP_STATE_ROOT: ${profileLauncherImage}`);
103
+ }
104
+ const configurationPath = config.launcherConfiguration
105
+ ? path.resolve(config.launcherConfiguration)
106
+ : undefined;
107
+ if (configurationPath && !isPathInside(stateRoot, configurationPath)) {
108
+ throw new Error(`Refusing launcher profile configuration outside PHARO_LAUNCHER_MCP_STATE_ROOT: ${configurationPath}`);
109
+ }
110
+ for (const directory of [
111
+ path.dirname(profileLauncherImage),
112
+ config.profile.imagesDir,
113
+ config.profile.vmsDir,
114
+ config.profile.templateSourcesDir,
115
+ config.profile.initScriptsDir,
116
+ config.profile.logsDir,
117
+ ...(configurationPath ? [path.dirname(configurationPath)] : []),
118
+ ]) {
119
+ fs.mkdirSync(directory, { recursive: true });
120
+ }
121
+ ensureProfileLauncherImage(config, profileLauncherImage);
122
+ if (!configurationPath) {
123
+ return;
124
+ }
125
+ const content = profileLauncherConfigurationContent(config.profile);
126
+ if (!fs.existsSync(configurationPath) ||
127
+ fs.readFileSync(configurationPath, "utf8") !== content) {
128
+ fs.writeFileSync(configurationPath, content, "utf8");
129
+ }
130
+ }
5
131
  function scriptCommandAndArgs(scriptPath, args, platform, bashPath, comspec) {
6
132
  if (shouldRunScriptThroughCommandShell(scriptPath, platform)) {
7
133
  return {
@@ -20,33 +146,90 @@ function scriptCommandAndArgs(scriptPath, args, platform, bashPath, comspec) {
20
146
  args: [...args],
21
147
  };
22
148
  }
149
+ function resolveBashPath(platform) {
150
+ if (platform === "win32") {
151
+ return "bash";
152
+ }
153
+ return (POSIX_BASH_PATH_CANDIDATES.find((candidate) => fs.existsSync(candidate)) ??
154
+ "bash");
155
+ }
156
+ function diagnosticProfileLines(env) {
157
+ return [
158
+ "PHARO_LAUNCHER_MCP_PROFILE",
159
+ "PHARO_LAUNCHER_MCP_STATE_ROOT",
160
+ "PHARO_LAUNCHER_MCP_IMAGES_DIR",
161
+ "PHARO_LAUNCHER_MCP_VMS_DIR",
162
+ "PHARO_LAUNCHER_MCP_TEMPLATE_SOURCES_DIR",
163
+ "PHARO_LAUNCHER_MCP_INIT_SCRIPTS_DIR",
164
+ "PHARO_LAUNCHER_MCP_LOGS_DIR",
165
+ ].flatMap((key) => {
166
+ const value = env[key];
167
+ return value ? [`${key}: ${value}`] : [];
168
+ });
169
+ }
170
+ export function launcherInvocationFailureDiagnostic(invocation, error) {
171
+ const pathValue = invocation.env.PATH ?? process.env.PATH ?? "";
172
+ return [
173
+ `Failed to start PharoLauncher CLI command: ${error.message}`,
174
+ `source: ${invocation.source}`,
175
+ `command: ${invocation.command}`,
176
+ `args: ${invocation.args.join(" ")}`,
177
+ `cwd: ${invocation.cwd}`,
178
+ `PATH: ${pathValue}`,
179
+ ...diagnosticProfileLines(invocation.env),
180
+ ].join("\n");
181
+ }
182
+ export function isDetachedImageLaunch(args) {
183
+ return (args[0] === "image" &&
184
+ args[1] === "launch" &&
185
+ args.includes("--detached"));
186
+ }
187
+ function isImageLaunch(args) {
188
+ return args[0] === "image" && args[1] === "launch";
189
+ }
190
+ export function launcherArgsForDetachedImageLaunch(args) {
191
+ return args.filter((arg) => arg !== "--detached");
192
+ }
193
+ function imageLaunchArgsAndDisplayMode(args, startTime) {
194
+ const displayModeIndex = args.indexOf("--displayMode");
195
+ if (displayModeIndex < 0) {
196
+ return { args: [...args], displayMode: "headless" };
197
+ }
198
+ const displayMode = args[displayModeIndex + 1];
199
+ if (displayMode !== "headless" && displayMode !== "interactive") {
200
+ return failedResult("Profile-scoped image launch displayMode must be headless or interactive.", startTime);
201
+ }
202
+ return {
203
+ args: args.filter((_arg, index) => index !== displayModeIndex && index !== displayModeIndex + 1),
204
+ displayMode,
205
+ };
206
+ }
207
+ function isImageCreateFromBuild(args) {
208
+ return args[0] === "image" && args[1] === "create" && args[2] === "fromBuild";
209
+ }
210
+ function profileScopedFromBuildDiagnostic(args, config) {
211
+ if (!config.profile || !isImageCreateFromBuild(args)) {
212
+ return undefined;
213
+ }
214
+ return [
215
+ "Refusing profile-scoped image create fromBuild before invoking Pharo Launcher.",
216
+ "Pharo Launcher currently applies the CLI profile imagesDirectory during creation, but fromBuild automatically launches the image without initializing PhLVirtualMachineManager from the CLI configuration.",
217
+ `That launch can download or run VMs outside PHARO_LAUNCHER_MCP_VMS_DIR (${config.profile.vmsDir}).`,
218
+ "Use a non-fromBuild creation path with explicit launch control, or fix Pharo Launcher to initialize the VM manager from the CLI configuration before fromBuild launch.",
219
+ ].join("\n");
220
+ }
23
221
  export function buildLauncherCliInvocation(args, config = loadPharoLauncherConfig(), options = {}) {
24
222
  const platform = options.platform ?? process.platform;
25
223
  const launcherArgs = config.launcherConfiguration
26
224
  ? ["--configuration", config.launcherConfiguration, ...args]
27
225
  : [...args];
28
- const env = {
29
- ...process.env,
30
- PHARO_LAUNCHER_IMAGE: config.launcherImage,
31
- PHARO_LAUNCHER_VM: config.launcherVm,
32
- ...(config.profile
33
- ? {
34
- PHARO_LAUNCHER_MCP_PROFILE: config.profile.name,
35
- PHARO_LAUNCHER_MCP_STATE_ROOT: config.profile.stateRoot,
36
- PHARO_LAUNCHER_MCP_IMAGES_DIR: config.profile.imagesDir,
37
- PHARO_LAUNCHER_MCP_VMS_DIR: config.profile.vmsDir,
38
- PHARO_LAUNCHER_MCP_TEMPLATE_SOURCES_DIR: config.profile.templateSourcesDir,
39
- PHARO_LAUNCHER_MCP_INIT_SCRIPTS_DIR: config.profile.initScriptsDir,
40
- PHARO_LAUNCHER_MCP_LOGS_DIR: config.profile.logsDir,
41
- }
42
- : {}),
43
- };
226
+ const env = launcherEnvironment(config);
44
227
  const launcherScript = config.launcherScript ??
45
228
  (options.resolveScript ?? ((value) => resolveLauncherScript({
46
229
  launcherDir: value.launcherDir,
47
230
  })))(config);
48
231
  if (launcherScript) {
49
- const commandAndArgs = scriptCommandAndArgs(launcherScript, launcherArgs, platform, options.bashPath, options.comspec ?? process.env.ComSpec);
232
+ const commandAndArgs = scriptCommandAndArgs(launcherScript, launcherArgs, platform, options.bashPath ?? resolveBashPath(platform), options.comspec ?? process.env.ComSpec);
50
233
  return {
51
234
  ...commandAndArgs,
52
235
  cwd: config.launcherDir,
@@ -69,36 +252,110 @@ export function buildLauncherCliInvocation(args, config = loadPharoLauncherConfi
69
252
  source: "direct",
70
253
  };
71
254
  }
72
- export function runLauncherCli(args, options = {}) {
73
- const timeoutMs = options.timeoutMs ?? 30_000;
74
- const startTime = Date.now();
75
- const invocation = buildLauncherCliInvocation(args, options.config ?? loadPharoLauncherConfig());
76
- return new Promise((resolve, reject) => {
77
- const child = spawn(invocation.command, invocation.args, {
78
- cwd: invocation.cwd,
79
- env: invocation.env,
80
- windowsHide: true,
81
- });
255
+ function failedResult(stderr, startTime, extra = {}) {
256
+ return {
257
+ exitCode: 1,
258
+ stdout: "",
259
+ stderr,
260
+ durationMs: Date.now() - startTime,
261
+ timedOut: false,
262
+ ...extra,
263
+ };
264
+ }
265
+ function validateInvocationSetup(invocation, startTime) {
266
+ if (invocation.source !== "script" || !path.isAbsolute(invocation.command)) {
267
+ return undefined;
268
+ }
269
+ try {
270
+ fs.accessSync(invocation.command, fs.constants.X_OK);
271
+ return undefined;
272
+ }
273
+ catch (error) {
274
+ const message = error instanceof Error
275
+ ? `Selected launcher shell path is missing or inaccessible before spawn: ${error.message}`
276
+ : "Selected launcher shell path is missing or inaccessible before spawn";
277
+ return failedResult(launcherInvocationFailureDiagnostic(invocation, new Error(message)), startTime);
278
+ }
279
+ }
280
+ function trimForDiagnostic(value) {
281
+ const trimmed = value.trim();
282
+ return trimmed.length > 0 ? trimmed : undefined;
283
+ }
284
+ function commandFailureDiagnostic(label, result) {
285
+ return [
286
+ `${label} failed.`,
287
+ `exitCode: ${result.exitCode ?? "unknown"}`,
288
+ `timedOut: ${result.timedOut}`,
289
+ ...(result.timeoutReason ? [`timeoutReason: ${result.timeoutReason}`] : []),
290
+ ...(trimForDiagnostic(result.stdout)
291
+ ? [`stdout:\n${trimForDiagnostic(result.stdout)}`]
292
+ : []),
293
+ ...(trimForDiagnostic(result.stderr)
294
+ ? [`stderr:\n${trimForDiagnostic(result.stderr)}`]
295
+ : []),
296
+ ].join("\n");
297
+ }
298
+ function runInvocation(invocation, timeoutMs, startTime) {
299
+ return new Promise((resolve) => {
300
+ let child;
301
+ try {
302
+ child = spawn(invocation.command, invocation.args, {
303
+ cwd: invocation.cwd,
304
+ env: invocation.env,
305
+ windowsHide: true,
306
+ });
307
+ }
308
+ catch (error) {
309
+ resolve({
310
+ exitCode: null,
311
+ stdout: "",
312
+ stderr: launcherInvocationFailureDiagnostic(invocation, error instanceof Error ? error : new Error(String(error))),
313
+ durationMs: Date.now() - startTime,
314
+ timedOut: false,
315
+ });
316
+ return;
317
+ }
82
318
  let stdout = "";
83
319
  let stderr = "";
84
320
  let timedOut = false;
85
321
  let timeoutReason;
322
+ const stdoutStream = child.stdout;
323
+ const stderrStream = child.stderr;
324
+ if (!stdoutStream || !stderrStream) {
325
+ child.kill();
326
+ resolve({
327
+ exitCode: null,
328
+ stdout,
329
+ stderr: launcherInvocationFailureDiagnostic(invocation, new Error("PharoLauncher CLI spawn did not provide stdout/stderr streams")),
330
+ durationMs: Date.now() - startTime,
331
+ timedOut,
332
+ });
333
+ return;
334
+ }
86
335
  const timeout = setTimeout(() => {
87
336
  timedOut = true;
88
337
  timeoutReason = `PharoLauncher CLI timed out after ${timeoutMs}ms`;
89
338
  child.kill();
90
339
  }, timeoutMs);
91
- child.stdout.setEncoding("utf8");
92
- child.stderr.setEncoding("utf8");
93
- child.stdout.on("data", (chunk) => {
340
+ stdoutStream.setEncoding("utf8");
341
+ stderrStream.setEncoding("utf8");
342
+ stdoutStream.on("data", (chunk) => {
94
343
  stdout += chunk;
95
344
  });
96
- child.stderr.on("data", (chunk) => {
345
+ stderrStream.on("data", (chunk) => {
97
346
  stderr += chunk;
98
347
  });
99
348
  child.on("error", (error) => {
100
349
  clearTimeout(timeout);
101
- reject(error);
350
+ const errnoError = error;
351
+ resolve({
352
+ exitCode: null,
353
+ stdout,
354
+ stderr: launcherInvocationFailureDiagnostic(invocation, errnoError),
355
+ durationMs: Date.now() - startTime,
356
+ timedOut,
357
+ ...(timeoutReason ? { timeoutReason } : {}),
358
+ });
102
359
  });
103
360
  child.on("close", (exitCode) => {
104
361
  clearTimeout(timeout);
@@ -113,4 +370,366 @@ export function runLauncherCli(args, options = {}) {
113
370
  });
114
371
  });
115
372
  }
373
+ function parsedImagesFromInfo(stdout) {
374
+ const parsed = parseLauncherOutput("pharo_launcher_image_info", "ston", stdout);
375
+ if (parsed.status !== "parsed") {
376
+ return undefined;
377
+ }
378
+ if (Array.isArray(parsed.data)) {
379
+ return parsed.data.filter((item) => typeof item === "object" && item !== null);
380
+ }
381
+ if (typeof parsed.data === "object" && parsed.data !== null) {
382
+ return [parsed.data];
383
+ }
384
+ return undefined;
385
+ }
386
+ function imageNameFromLaunchArgs(args) {
387
+ const candidate = args.at(-1);
388
+ return candidate && !candidate.startsWith("--") ? candidate : undefined;
389
+ }
390
+ function scriptPathFromLaunchArgs(args) {
391
+ const scriptIndex = args.indexOf("--script");
392
+ return scriptIndex >= 0 ? args[scriptIndex + 1] : undefined;
393
+ }
394
+ function normalizePharoVersion(value) {
395
+ const trimmed = value.trim();
396
+ const numeric = trimmed.match(/^(\d{2,3})(?:\.(\d+))?$/);
397
+ if (!numeric) {
398
+ return trimmed;
399
+ }
400
+ const major = numeric[1];
401
+ const minor = numeric[2] ?? (major.length === 2 ? "0" : "");
402
+ return `${major}${minor}`;
403
+ }
404
+ function pharoVersionFromTemplate(image) {
405
+ const template = image.originTemplate;
406
+ const urlVersion = template?.url?.match(/(?:^|[/-])(\d{2,3})(?:[./-]|$)/)?.[1];
407
+ if (urlVersion) {
408
+ return normalizePharoVersion(urlVersion);
409
+ }
410
+ const nameVersion = template?.name?.match(/\b(?:Pharo|Moose)\D*(\d{2,3}(?:\.\d+)?)/i)?.[1];
411
+ return nameVersion ? normalizePharoVersion(nameVersion) : undefined;
412
+ }
413
+ function vmArchitectureSegment(image) {
414
+ const source = `${image.architecture ?? ""} ${image.originTemplate?.name ?? ""} ${image.originTemplate?.url ?? ""}`;
415
+ if (/\b(?:aarch64|arm64)\b/i.test(source)) {
416
+ return "aarch64";
417
+ }
418
+ if (/\b(?:x86|32\s*[- ]?\s*bit|32bit)\b/i.test(source)) {
419
+ return "x86";
420
+ }
421
+ return "x64";
422
+ }
423
+ function imageVmId(image) {
424
+ if (image?.vmId) {
425
+ return image.vmId;
426
+ }
427
+ if (!image) {
428
+ return undefined;
429
+ }
430
+ const pharoVersion = image.pharoVersion ?? pharoVersionFromTemplate(image);
431
+ return pharoVersion
432
+ ? `${pharoVersion}-${vmArchitectureSegment(image)}`
433
+ : undefined;
434
+ }
435
+ function profileImagePath(profile, imageName, image) {
436
+ const imagePath = image?.imagePath ?? path.join(imageName, `${imageName}.image`);
437
+ return path.isAbsolute(imagePath)
438
+ ? path.resolve(imagePath)
439
+ : path.resolve(profile.imagesDir, imagePath);
440
+ }
441
+ function profileVmDirectory(profile, vmId) {
442
+ const vmDirectory = path.resolve(profile.vmsDir, vmId);
443
+ return isPathInside(profile.vmsDir, vmDirectory) ? vmDirectory : undefined;
444
+ }
445
+ function profileVmExecutableCandidates(vmDirectory) {
446
+ return [
447
+ path.join(vmDirectory, "Pharo.app", "Contents", "MacOS", "Pharo"),
448
+ path.join(vmDirectory, "Pharo.exe"),
449
+ path.join(vmDirectory, "PharoConsole.exe"),
450
+ path.join(vmDirectory, "pharo"),
451
+ path.join(vmDirectory, "pharo-vm", "pharo"),
452
+ ];
453
+ }
454
+ function looksLikeVmExecutable(filePath) {
455
+ return /^(?:Pharo|PharoConsole|pharo)(?:\.exe)?$/i.test(path.basename(filePath));
456
+ }
457
+ function scanForVmExecutable(vmDirectory) {
458
+ const stack = [vmDirectory];
459
+ let visited = 0;
460
+ while (stack.length > 0 && visited < 5_000) {
461
+ const current = stack.pop();
462
+ visited += 1;
463
+ let entries;
464
+ try {
465
+ entries = fs.readdirSync(current, { withFileTypes: true });
466
+ }
467
+ catch {
468
+ continue;
469
+ }
470
+ for (const entry of entries) {
471
+ const entryPath = path.join(current, entry.name);
472
+ if (entry.isDirectory()) {
473
+ stack.push(entryPath);
474
+ }
475
+ else if (entry.isFile() && looksLikeVmExecutable(entryPath)) {
476
+ return entryPath;
477
+ }
478
+ }
479
+ }
480
+ return undefined;
481
+ }
482
+ function resolveProfileVmExecutable(profile, vmId) {
483
+ const vmDirectory = profileVmDirectory(profile, vmId);
484
+ if (!vmDirectory) {
485
+ return undefined;
486
+ }
487
+ const knownCandidate = profileVmExecutableCandidates(vmDirectory).find((candidate) => isPathInside(profile.vmsDir, candidate) && fs.existsSync(candidate));
488
+ if (knownCandidate) {
489
+ return knownCandidate;
490
+ }
491
+ const scanned = scanForVmExecutable(vmDirectory);
492
+ return scanned && isPathInside(profile.vmsDir, scanned) ? scanned : undefined;
493
+ }
494
+ async function launcherCliSubcommand(args, config, timeoutMs) {
495
+ const invocation = buildLauncherCliInvocation(args, config);
496
+ return runInvocation(invocation, timeoutMs, Date.now());
497
+ }
498
+ async function profileScopedImageLaunchPlan(args, config, timeoutMs, startTime, displayMode) {
499
+ const profile = config.profile;
500
+ const imageName = imageNameFromLaunchArgs(args);
501
+ if (!profile || !imageName) {
502
+ return failedResult("Profile-scoped image launch could not determine the requested image name.", startTime);
503
+ }
504
+ const infoArgs = ["image", "info", "--ston", imageName];
505
+ const infoResult = await launcherCliSubcommand(infoArgs, config, timeoutMs);
506
+ if (infoResult.exitCode !== 0 || infoResult.timedOut) {
507
+ return failedResult([
508
+ `Profile-scoped image launch could not inspect image ${imageName}.`,
509
+ commandFailureDiagnostic("pharo_launcher_image_info", infoResult),
510
+ ].join("\n"), startTime, {
511
+ timedOut: infoResult.timedOut,
512
+ ...(infoResult.timeoutReason
513
+ ? { timeoutReason: infoResult.timeoutReason }
514
+ : {}),
515
+ });
516
+ }
517
+ const images = parsedImagesFromInfo(infoResult.stdout);
518
+ const image = images?.find((candidate) => candidate.name === imageName) ?? images?.[0];
519
+ const imagePath = profileImagePath(profile, imageName, image);
520
+ if (!isPathInside(profile.imagesDir, imagePath)) {
521
+ return failedResult([
522
+ `Profile-scoped image launch refused image path outside PHARO_LAUNCHER_MCP_IMAGES_DIR (${profile.imagesDir}).`,
523
+ `image: ${imagePath}`,
524
+ ].join("\n"), startTime);
525
+ }
526
+ if (!fs.existsSync(imagePath)) {
527
+ return failedResult([
528
+ `Profile-scoped image launch could not find image file for ${imageName}.`,
529
+ `expected: ${imagePath}`,
530
+ ].join("\n"), startTime);
531
+ }
532
+ const vmId = imageVmId(image);
533
+ if (!vmId) {
534
+ return failedResult(`Profile-scoped image launch could not determine a VM id for image ${imageName}.`, startTime);
535
+ }
536
+ let vmPath = resolveProfileVmExecutable(profile, vmId);
537
+ let vmUpdated = false;
538
+ if (!vmPath) {
539
+ const updateResult = await launcherCliSubcommand(["vm", "update", vmId], config, Math.max(timeoutMs, 120_000));
540
+ vmUpdated = updateResult.exitCode === 0 && !updateResult.timedOut;
541
+ if (!vmUpdated) {
542
+ return failedResult([
543
+ `Profile-scoped image launch could not install VM ${vmId} inside PHARO_LAUNCHER_MCP_VMS_DIR (${profile.vmsDir}).`,
544
+ commandFailureDiagnostic("pharo_launcher_vm_update", updateResult),
545
+ ].join("\n"), startTime, {
546
+ timedOut: updateResult.timedOut,
547
+ ...(updateResult.timeoutReason
548
+ ? { timeoutReason: updateResult.timeoutReason }
549
+ : {}),
550
+ });
551
+ }
552
+ vmPath = resolveProfileVmExecutable(profile, vmId);
553
+ }
554
+ if (!vmPath) {
555
+ return failedResult([
556
+ `Profile-scoped image launch could not resolve a profile-local VM executable for ${vmId} after VM update.`,
557
+ `PHARO_LAUNCHER_MCP_VMS_DIR: ${profile.vmsDir}`,
558
+ ].join("\n"), startTime);
559
+ }
560
+ const scriptPath = scriptPathFromLaunchArgs(args);
561
+ const invocationArgs = [
562
+ ...(displayMode === "headless" ? ["--headless"] : []),
563
+ imagePath,
564
+ ...(scriptPath ? ["eval", scriptPath] : []),
565
+ ];
566
+ return {
567
+ imageName,
568
+ imagePath,
569
+ ...(scriptPath ? { scriptPath } : {}),
570
+ displayMode,
571
+ vmId,
572
+ vmPath,
573
+ invocation: {
574
+ command: vmPath,
575
+ args: invocationArgs,
576
+ cwd: path.dirname(imagePath),
577
+ env: launcherEnvironment(config),
578
+ source: "direct",
579
+ },
580
+ vmUpdated,
581
+ };
582
+ }
583
+ async function runDetachedProfileImageLaunch(plan, config, args, startTime) {
584
+ const logPaths = detachedLaunchLogPaths(config, args, startTime);
585
+ fs.mkdirSync(path.dirname(logPaths.stdoutPath), { recursive: true });
586
+ const stdoutFd = fs.openSync(logPaths.stdoutPath, "a");
587
+ let stderrFd;
588
+ try {
589
+ stderrFd = fs.openSync(logPaths.stderrPath, "a");
590
+ const child = spawn(plan.invocation.command, plan.invocation.args, {
591
+ cwd: plan.invocation.cwd,
592
+ env: plan.invocation.env,
593
+ detached: true,
594
+ stdio: ["ignore", stdoutFd, stderrFd],
595
+ windowsHide: true,
596
+ });
597
+ child.on("error", () => {
598
+ // Detached launches cannot report async spawn failures to the already
599
+ // returned result, but the listener prevents an unhandled error event.
600
+ });
601
+ child.unref();
602
+ return {
603
+ exitCode: 0,
604
+ stdout: [
605
+ `Detached profile-scoped Pharo image pid ${child.pid ?? "unknown"}.`,
606
+ `image: ${plan.imagePath}`,
607
+ `displayMode: ${plan.displayMode}`,
608
+ `vm: ${plan.vmPath}`,
609
+ `vmId: ${plan.vmId}`,
610
+ `vmUpdated: ${plan.vmUpdated}`,
611
+ `stdout: ${logPaths.stdoutPath}`,
612
+ `stderr: ${logPaths.stderrPath}`,
613
+ ].join("\n"),
614
+ stderr: "",
615
+ durationMs: Date.now() - startTime,
616
+ timedOut: false,
617
+ };
618
+ }
619
+ finally {
620
+ fs.closeSync(stdoutFd);
621
+ if (stderrFd !== undefined) {
622
+ fs.closeSync(stderrFd);
623
+ }
624
+ }
625
+ }
626
+ async function runProfileScopedImageLaunch(args, config, timeoutMs, startTime, detached, displayMode) {
627
+ ensureProfileLauncherConfiguration(config);
628
+ const plan = await profileScopedImageLaunchPlan(args, config, timeoutMs, startTime, displayMode);
629
+ if ("exitCode" in plan) {
630
+ return plan;
631
+ }
632
+ if (detached) {
633
+ const setupFailure = validateInvocationSetup(plan.invocation, startTime);
634
+ if (setupFailure) {
635
+ return setupFailure;
636
+ }
637
+ return runDetachedProfileImageLaunch(plan, config, args, startTime);
638
+ }
639
+ const setupFailure = validateInvocationSetup(plan.invocation, startTime);
640
+ if (setupFailure) {
641
+ return setupFailure;
642
+ }
643
+ const result = await runInvocation(plan.invocation, timeoutMs, startTime);
644
+ return {
645
+ ...result,
646
+ stdout: [
647
+ `Profile-scoped Pharo image launch.`,
648
+ `image: ${plan.imagePath}`,
649
+ `displayMode: ${plan.displayMode}`,
650
+ `vm: ${plan.vmPath}`,
651
+ `vmId: ${plan.vmId}`,
652
+ `vmUpdated: ${plan.vmUpdated}`,
653
+ result.stdout,
654
+ ]
655
+ .filter((line) => line.length > 0)
656
+ .join("\n"),
657
+ };
658
+ }
659
+ export function runLauncherCli(args, options = {}) {
660
+ const timeoutMs = options.timeoutMs ?? 30_000;
661
+ const startTime = Date.now();
662
+ const detachedImageLaunch = isDetachedImageLaunch(args);
663
+ const invocationArgs = detachedImageLaunch
664
+ ? launcherArgsForDetachedImageLaunch(args)
665
+ : args;
666
+ const imageLaunchOptions = isImageLaunch(invocationArgs)
667
+ ? imageLaunchArgsAndDisplayMode(invocationArgs, startTime)
668
+ : { args: [...invocationArgs], displayMode: "headless" };
669
+ if ("exitCode" in imageLaunchOptions) {
670
+ return Promise.resolve(imageLaunchOptions);
671
+ }
672
+ const launcherArgs = imageLaunchOptions.args;
673
+ const config = options.config ?? loadPharoLauncherConfig();
674
+ const scopedFromBuildDiagnostic = profileScopedFromBuildDiagnostic(launcherArgs, config);
675
+ if (scopedFromBuildDiagnostic) {
676
+ return Promise.resolve({
677
+ exitCode: 1,
678
+ stdout: "",
679
+ stderr: scopedFromBuildDiagnostic,
680
+ durationMs: Date.now() - startTime,
681
+ timedOut: false,
682
+ });
683
+ }
684
+ if (config.profile && isImageLaunch(launcherArgs)) {
685
+ return runProfileScopedImageLaunch(launcherArgs, config, timeoutMs, startTime, detachedImageLaunch, imageLaunchOptions.displayMode);
686
+ }
687
+ ensureProfileLauncherConfiguration(config);
688
+ const invocation = buildLauncherCliInvocation(launcherArgs, config, {
689
+ bashPath: options.bashPath,
690
+ });
691
+ const setupFailure = validateInvocationSetup(invocation, startTime);
692
+ if (setupFailure) {
693
+ return Promise.resolve(setupFailure);
694
+ }
695
+ if (detachedImageLaunch) {
696
+ const logPaths = detachedLaunchLogPaths(config, args, startTime);
697
+ fs.mkdirSync(path.dirname(logPaths.stdoutPath), { recursive: true });
698
+ const stdoutFd = fs.openSync(logPaths.stdoutPath, "a");
699
+ let stderrFd;
700
+ try {
701
+ stderrFd = fs.openSync(logPaths.stderrPath, "a");
702
+ const child = spawn(invocation.command, invocation.args, {
703
+ cwd: invocation.cwd,
704
+ env: invocation.env,
705
+ detached: true,
706
+ stdio: ["ignore", stdoutFd, stderrFd],
707
+ windowsHide: true,
708
+ });
709
+ child.on("error", () => {
710
+ // Detached launches cannot report async spawn failures to the already
711
+ // returned result, but the listener prevents an unhandled error event.
712
+ });
713
+ child.unref();
714
+ return Promise.resolve({
715
+ exitCode: 0,
716
+ stdout: [
717
+ `Detached PharoLauncher CLI pid ${child.pid ?? "unknown"}.`,
718
+ `stdout: ${logPaths.stdoutPath}`,
719
+ `stderr: ${logPaths.stderrPath}`,
720
+ ].join("\n"),
721
+ stderr: "",
722
+ durationMs: Date.now() - startTime,
723
+ timedOut: false,
724
+ });
725
+ }
726
+ finally {
727
+ fs.closeSync(stdoutFd);
728
+ if (stderrFd !== undefined) {
729
+ fs.closeSync(stderrFd);
730
+ }
731
+ }
732
+ }
733
+ return runInvocation(invocation, timeoutMs, startTime);
734
+ }
116
735
  //# sourceMappingURL=launcherCli.js.map