@evref-bl/pharo-launcher-mcp 0.1.2 → 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 +229 -199
  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 +75 -6
  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 +1 -0
  20. package/dist/imageMetadata.d.ts.map +1 -1
  21. package/dist/imageMetadata.js +35 -2
  22. package/dist/imageMetadata.js.map +1 -1
  23. package/dist/launcherCli.d.ts +2 -0
  24. package/dist/launcherCli.d.ts.map +1 -1
  25. package/dist/launcherCli.js +561 -62
  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 +47 -0
  35. package/dist/resultNormalizer.js.map +1 -1
  36. package/dist/server.d.ts +2 -0
  37. package/dist/server.d.ts.map +1 -1
  38. package/dist/server.js +387 -10
  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 +59 -23
  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 +57 -52
@@ -3,7 +3,9 @@ import fs from "node:fs";
3
3
  import path from "node:path";
4
4
  import { loadPharoLauncherConfig, } from "./config.js";
5
5
  import { resolveLauncherScript } from "./launcherScript.js";
6
+ import { parseLauncherOutput } from "./parser.js";
6
7
  import { shouldRunScriptThroughBash, shouldRunScriptThroughCommandShell, } from "./platform.js";
8
+ const POSIX_BASH_PATH_CANDIDATES = ["/bin/bash", "/usr/bin/bash"];
7
9
  function comparablePath(value) {
8
10
  const resolved = path.resolve(value);
9
11
  return process.platform === "win32" ? resolved.toLowerCase() : resolved;
@@ -36,6 +38,24 @@ function detachedLaunchLogPaths(config, args, startTime) {
36
38
  stderrPath: path.join(logsDir, `${baseName}.err.log`),
37
39
  };
38
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
+ }
39
59
  export function profileLauncherConfigurationContent(profile) {
40
60
  return [
41
61
  "PharoLauncherCLIConfiguration {",
@@ -48,26 +68,60 @@ export function profileLauncherConfigurationContent(profile) {
48
68
  "",
49
69
  ].join("\n");
50
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
+ }
51
95
  export function ensureProfileLauncherConfiguration(config) {
52
- if (!config.profile || !config.launcherConfiguration) {
96
+ if (!config.profile) {
53
97
  return;
54
98
  }
55
- const configurationPath = path.resolve(config.launcherConfiguration);
56
99
  const stateRoot = path.resolve(config.profile.stateRoot);
57
- if (!isPathInside(stateRoot, configurationPath)) {
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)) {
58
108
  throw new Error(`Refusing launcher profile configuration outside PHARO_LAUNCHER_MCP_STATE_ROOT: ${configurationPath}`);
59
109
  }
60
110
  for (const directory of [
61
- path.dirname(config.profile.launcherImage),
111
+ path.dirname(profileLauncherImage),
62
112
  config.profile.imagesDir,
63
113
  config.profile.vmsDir,
64
114
  config.profile.templateSourcesDir,
65
115
  config.profile.initScriptsDir,
66
116
  config.profile.logsDir,
67
- path.dirname(configurationPath),
117
+ ...(configurationPath ? [path.dirname(configurationPath)] : []),
68
118
  ]) {
69
119
  fs.mkdirSync(directory, { recursive: true });
70
120
  }
121
+ ensureProfileLauncherImage(config, profileLauncherImage);
122
+ if (!configurationPath) {
123
+ return;
124
+ }
71
125
  const content = profileLauncherConfigurationContent(config.profile);
72
126
  if (!fs.existsSync(configurationPath) ||
73
127
  fs.readFileSync(configurationPath, "utf8") !== content) {
@@ -92,41 +146,90 @@ function scriptCommandAndArgs(scriptPath, args, platform, bashPath, comspec) {
92
146
  args: [...args],
93
147
  };
94
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
+ }
95
182
  export function isDetachedImageLaunch(args) {
96
183
  return (args[0] === "image" &&
97
184
  args[1] === "launch" &&
98
185
  args.includes("--detached"));
99
186
  }
187
+ function isImageLaunch(args) {
188
+ return args[0] === "image" && args[1] === "launch";
189
+ }
100
190
  export function launcherArgsForDetachedImageLaunch(args) {
101
191
  return args.filter((arg) => arg !== "--detached");
102
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
+ }
103
221
  export function buildLauncherCliInvocation(args, config = loadPharoLauncherConfig(), options = {}) {
104
222
  const platform = options.platform ?? process.platform;
105
223
  const launcherArgs = config.launcherConfiguration
106
224
  ? ["--configuration", config.launcherConfiguration, ...args]
107
225
  : [...args];
108
- const env = {
109
- ...process.env,
110
- PHARO_LAUNCHER_IMAGE: config.launcherImage,
111
- PHARO_LAUNCHER_VM: config.launcherVm,
112
- ...(config.profile
113
- ? {
114
- PHARO_LAUNCHER_MCP_PROFILE: config.profile.name,
115
- PHARO_LAUNCHER_MCP_STATE_ROOT: config.profile.stateRoot,
116
- PHARO_LAUNCHER_MCP_IMAGES_DIR: config.profile.imagesDir,
117
- PHARO_LAUNCHER_MCP_VMS_DIR: config.profile.vmsDir,
118
- PHARO_LAUNCHER_MCP_TEMPLATE_SOURCES_DIR: config.profile.templateSourcesDir,
119
- PHARO_LAUNCHER_MCP_INIT_SCRIPTS_DIR: config.profile.initScriptsDir,
120
- PHARO_LAUNCHER_MCP_LOGS_DIR: config.profile.logsDir,
121
- }
122
- : {}),
123
- };
226
+ const env = launcherEnvironment(config);
124
227
  const launcherScript = config.launcherScript ??
125
228
  (options.resolveScript ?? ((value) => resolveLauncherScript({
126
229
  launcherDir: value.launcherDir,
127
230
  })))(config);
128
231
  if (launcherScript) {
129
- 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);
130
233
  return {
131
234
  ...commandAndArgs,
132
235
  cwd: config.launcherDir,
@@ -149,6 +252,410 @@ export function buildLauncherCliInvocation(args, config = loadPharoLauncherConfi
149
252
  source: "direct",
150
253
  };
151
254
  }
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
+ }
318
+ let stdout = "";
319
+ let stderr = "";
320
+ let timedOut = false;
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
+ }
335
+ const timeout = setTimeout(() => {
336
+ timedOut = true;
337
+ timeoutReason = `PharoLauncher CLI timed out after ${timeoutMs}ms`;
338
+ child.kill();
339
+ }, timeoutMs);
340
+ stdoutStream.setEncoding("utf8");
341
+ stderrStream.setEncoding("utf8");
342
+ stdoutStream.on("data", (chunk) => {
343
+ stdout += chunk;
344
+ });
345
+ stderrStream.on("data", (chunk) => {
346
+ stderr += chunk;
347
+ });
348
+ child.on("error", (error) => {
349
+ clearTimeout(timeout);
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
+ });
359
+ });
360
+ child.on("close", (exitCode) => {
361
+ clearTimeout(timeout);
362
+ resolve({
363
+ exitCode,
364
+ stdout,
365
+ stderr,
366
+ durationMs: Date.now() - startTime,
367
+ timedOut,
368
+ ...(timeoutReason ? { timeoutReason } : {}),
369
+ });
370
+ });
371
+ });
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
+ }
152
659
  export function runLauncherCli(args, options = {}) {
153
660
  const timeoutMs = options.timeoutMs ?? 30_000;
154
661
  const startTime = Date.now();
@@ -156,9 +663,35 @@ export function runLauncherCli(args, options = {}) {
156
663
  const invocationArgs = detachedImageLaunch
157
664
  ? launcherArgsForDetachedImageLaunch(args)
158
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;
159
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
+ }
160
687
  ensureProfileLauncherConfiguration(config);
161
- const invocation = buildLauncherCliInvocation(invocationArgs, 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
+ }
162
695
  if (detachedImageLaunch) {
163
696
  const logPaths = detachedLaunchLogPaths(config, args, startTime);
164
697
  fs.mkdirSync(path.dirname(logPaths.stdoutPath), { recursive: true });
@@ -173,6 +706,10 @@ export function runLauncherCli(args, options = {}) {
173
706
  stdio: ["ignore", stdoutFd, stderrFd],
174
707
  windowsHide: true,
175
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
+ });
176
713
  child.unref();
177
714
  return Promise.resolve({
178
715
  exitCode: 0,
@@ -193,44 +730,6 @@ export function runLauncherCli(args, options = {}) {
193
730
  }
194
731
  }
195
732
  }
196
- return new Promise((resolve, reject) => {
197
- const child = spawn(invocation.command, invocation.args, {
198
- cwd: invocation.cwd,
199
- env: invocation.env,
200
- windowsHide: true,
201
- });
202
- let stdout = "";
203
- let stderr = "";
204
- let timedOut = false;
205
- let timeoutReason;
206
- const timeout = setTimeout(() => {
207
- timedOut = true;
208
- timeoutReason = `PharoLauncher CLI timed out after ${timeoutMs}ms`;
209
- child.kill();
210
- }, timeoutMs);
211
- child.stdout.setEncoding("utf8");
212
- child.stderr.setEncoding("utf8");
213
- child.stdout.on("data", (chunk) => {
214
- stdout += chunk;
215
- });
216
- child.stderr.on("data", (chunk) => {
217
- stderr += chunk;
218
- });
219
- child.on("error", (error) => {
220
- clearTimeout(timeout);
221
- reject(error);
222
- });
223
- child.on("close", (exitCode) => {
224
- clearTimeout(timeout);
225
- resolve({
226
- exitCode,
227
- stdout,
228
- stderr,
229
- durationMs: Date.now() - startTime,
230
- timedOut,
231
- ...(timeoutReason ? { timeoutReason } : {}),
232
- });
233
- });
234
- });
733
+ return runInvocation(invocation, timeoutMs, startTime);
235
734
  }
236
735
  //# sourceMappingURL=launcherCli.js.map