@camunda8/cli 4.7.0-alpha.20 → 4.7.0-alpha.22

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 (91) hide show
  1. package/PLUGIN-HELP.md +1 -1
  2. package/README.md +0 -3
  3. package/dist/command-dispatch.d.ts.map +1 -1
  4. package/dist/command-dispatch.js +0 -8
  5. package/dist/command-dispatch.js.map +1 -1
  6. package/dist/commands/run.d.ts +0 -5
  7. package/dist/commands/run.d.ts.map +1 -1
  8. package/dist/commands/run.js +1 -9
  9. package/dist/commands/run.js.map +1 -1
  10. package/dist/core/errors.d.ts +17 -0
  11. package/dist/core/errors.d.ts.map +1 -1
  12. package/dist/core/errors.js +32 -0
  13. package/dist/core/errors.js.map +1 -1
  14. package/dist/default-plugins/modeler/README.md +12 -0
  15. package/dist/default-plugins/modeler/c8ctl-plugin.js +3042 -0
  16. package/dist/default-plugins/modeler/package.json +8 -0
  17. package/dist/default-plugins/setup/README.md +36 -0
  18. package/dist/default-plugins/setup/c8ctl-plugin.js +6423 -0
  19. package/dist/default-plugins/setup/package.json +8 -0
  20. package/dist/default-plugins/skills/README.md +27 -0
  21. package/dist/default-plugins/skills/c8ctl-plugin.js +985 -0
  22. package/dist/default-plugins/skills/package.json +8 -0
  23. package/dist/framework/argv-parser.d.ts +14 -0
  24. package/dist/framework/argv-parser.d.ts.map +1 -1
  25. package/dist/framework/argv-parser.js +25 -0
  26. package/dist/framework/argv-parser.js.map +1 -1
  27. package/dist/framework/command-registry.d.ts +0 -76
  28. package/dist/framework/command-registry.d.ts.map +1 -1
  29. package/dist/framework/command-registry.js +0 -161
  30. package/dist/framework/command-registry.js.map +1 -1
  31. package/dist/framework/plugins/plugin-loader.d.ts +20 -2
  32. package/dist/framework/plugins/plugin-loader.d.ts.map +1 -1
  33. package/dist/framework/plugins/plugin-loader.js.map +1 -1
  34. package/dist/framework/ui/help.d.ts.map +1 -1
  35. package/dist/framework/ui/help.js +26 -13
  36. package/dist/framework/ui/help.js.map +1 -1
  37. package/dist/index.d.ts.map +1 -1
  38. package/dist/index.js +64 -11
  39. package/dist/index.js.map +1 -1
  40. package/dist/utils/command-local/mcp-install-helpers.d.ts +17 -0
  41. package/dist/utils/command-local/mcp-install-helpers.d.ts.map +1 -1
  42. package/dist/utils/command-local/mcp-install-helpers.js +23 -9
  43. package/dist/utils/command-local/mcp-install-helpers.js.map +1 -1
  44. package/dist/utils/command-local/process-instance-helpers.d.ts +6 -0
  45. package/dist/utils/command-local/process-instance-helpers.d.ts.map +1 -1
  46. package/dist/utils/command-local/process-instance-helpers.js +9 -0
  47. package/dist/utils/command-local/process-instance-helpers.js.map +1 -1
  48. package/dist/utils/command-local/skills-install-helpers.d.ts.map +1 -1
  49. package/dist/utils/command-local/skills-install-helpers.js +99 -1
  50. package/dist/utils/command-local/skills-install-helpers.js.map +1 -1
  51. package/dist/utils/index.d.ts +0 -6
  52. package/dist/utils/index.d.ts.map +1 -1
  53. package/dist/utils/index.js +0 -6
  54. package/dist/utils/index.js.map +1 -1
  55. package/package.json +1 -1
  56. package/dist/commands/modeler.d.ts +0 -10
  57. package/dist/commands/modeler.d.ts.map +0 -1
  58. package/dist/commands/modeler.js +0 -604
  59. package/dist/commands/modeler.js.map +0 -1
  60. package/dist/commands/setup.d.ts +0 -39
  61. package/dist/commands/setup.d.ts.map +0 -1
  62. package/dist/commands/setup.js +0 -856
  63. package/dist/commands/setup.js.map +0 -1
  64. package/dist/commands/skills.d.ts +0 -2
  65. package/dist/commands/skills.d.ts.map +0 -1
  66. package/dist/commands/skills.js +0 -38
  67. package/dist/commands/skills.js.map +0 -1
  68. package/dist/utils/command-local/blueprint-scaffold.d.ts +0 -151
  69. package/dist/utils/command-local/blueprint-scaffold.d.ts.map +0 -1
  70. package/dist/utils/command-local/blueprint-scaffold.js +0 -547
  71. package/dist/utils/command-local/blueprint-scaffold.js.map +0 -1
  72. package/dist/utils/command-local/modeler-helpers.d.ts +0 -15
  73. package/dist/utils/command-local/modeler-helpers.d.ts.map +0 -1
  74. package/dist/utils/command-local/modeler-helpers.js +0 -67
  75. package/dist/utils/command-local/modeler-helpers.js.map +0 -1
  76. package/dist/utils/command-local/setup-detectors.d.ts +0 -51
  77. package/dist/utils/command-local/setup-detectors.d.ts.map +0 -1
  78. package/dist/utils/command-local/setup-detectors.js +0 -115
  79. package/dist/utils/command-local/setup-detectors.js.map +0 -1
  80. package/dist/utils/command-local/setup-helpers.d.ts +0 -179
  81. package/dist/utils/command-local/setup-helpers.d.ts.map +0 -1
  82. package/dist/utils/command-local/setup-helpers.js +0 -374
  83. package/dist/utils/command-local/setup-helpers.js.map +0 -1
  84. package/dist/utils/command-local/setup-prerequisites.d.ts +0 -67
  85. package/dist/utils/command-local/setup-prerequisites.d.ts.map +0 -1
  86. package/dist/utils/command-local/setup-prerequisites.js +0 -238
  87. package/dist/utils/command-local/setup-prerequisites.js.map +0 -1
  88. package/dist/utils/command-local/setup-removal.d.ts +0 -37
  89. package/dist/utils/command-local/setup-removal.d.ts.map +0 -1
  90. package/dist/utils/command-local/setup-removal.js +0 -82
  91. package/dist/utils/command-local/setup-removal.js.map +0 -1
@@ -1,856 +0,0 @@
1
- /**
2
- * `c8ctl setup` — guided first-run setup for local Camunda 8 development.
3
- *
4
- * Prints the welcome banner, asks what to set up (checkbox list with
5
- * dependencies plus a blueprint choice), then runs every selected step.
6
- * While a step runs on a terminal, a braille spinner ticks on its open
7
- * title line so long steps don't look frozen (piped and --quiet output
8
- * stays static). Each step ends in a `[SUCCESS]`, `[ERROR]` or
9
- * `[SKIPPED]` line in an aligned column (green, red and dim on a
10
- * terminal); a failed step
11
- * prints its error on the following lines and the remaining steps still
12
- * run. Steps whose dependencies failed are skipped with the unmet steps
13
- * named.
14
- *
15
- * The browser opens once: c8run itself opens it when the cluster
16
- * reports healthy, exactly as on a plain `c8ctl cluster start`.
17
- *
18
- * Execution needs a go-ahead: an interactive selection or `--yes`. A
19
- * piped run without `--yes` and JSON mode print the plan payload only,
20
- * so a script never installs software by accident.
21
- *
22
- * Streams: the banner, prompts and progress are UI chrome on stderr; the
23
- * step report and the JSON payload are the command's answer on stdout.
24
- *
25
- * Exit codes: 0 when every selected step succeeded, or when nothing
26
- * was installed for lack of a go-ahead (the wizard was cancelled with
27
- * Escape — Ctrl+C ends it by signal, 130 on POSIX shells — a piped,
28
- * --quiet or JSON-mode run had no --yes, or --json / --dry-run printed
29
- * the plan only). A re-run reuses finished work where possible; it
30
- * repeats the blueprint deploy and start by design, leaves correct MCP
31
- * entries untouched, updates out-of-date skills, and installs missing
32
- * skills.
33
- * 1 when arguments failed validation or any step failed — the
34
- * remaining eligible steps still ran, dependents of a failed step (and
35
- * the deploy finale after any failure) were skipped, and re-running
36
- * picks up where the failure left off.
37
- */
38
- import { spawn } from "node:child_process";
39
- import { readFileSync, realpathSync } from "node:fs";
40
- import { extname, join, resolve } from "node:path";
41
- import { ProcessDefinitionId, TenantId, } from "@camunda8/orchestration-cluster-api";
42
- import { createClient, DEFAULT_PROFILE, SilentError } from "../core/index.js";
43
- import { defineCommand, isInteractive, multiSelect, select, } from "../framework/index.js";
44
- import { CAMUNDA_SKILLS_REPOSITORY, checkLocalClusterHealth, checkPrerequisites, createLineForwarder, defaultSelection, detectInstalledHarnesses, enforceComponentDependencies, formatStepResult, formatStepStatusSuffix, inspectSetupRemovalInventory, isClusterProgressLine, MANUAL_SETUP_LINKS, planMcpConfigs, removeCamundaSkill, removeSetupBlueprint, renderNextSteps, renderWelcomeBanner, runSkillInstall, SETUP_BLUEPRINTS, SETUP_COMPONENTS, SETUP_STEPS, scaffoldSetupBlueprint, setupBlueprintById, setupPlanPayload, startStepSpinner, writeMcpConfig, } from "../utils/index.js";
45
- import { deployResources } from "./helpers/deploy-helpers.js";
46
- import { buildMcpConnection } from "./mcp.js";
47
- import { installDesktopModeler } from "./modeler.js";
48
- import { extractProcessId } from "./run.js";
49
- /**
50
- * The tenant of a fresh local C8Run cluster. Pinned explicitly: tenant
51
- * resolution otherwise prefers the session tenant and
52
- * CAMUNDA_DEFAULT_TENANT_ID, which could name a remote tenant the local
53
- * cluster does not know.
54
- */
55
- const LOCAL_TENANT_ID = "<default>";
56
- /**
57
- * Explicit flags override the checkbox selection: --no-modeler wins.
58
- * Dependencies are then re-enforced, so a flag cannot resurrect a
59
- * component whose requirement is deselected.
60
- */
61
- function applyComponentFlags(selected, flags) {
62
- const next = new Set(selected);
63
- if (flags["no-modeler"])
64
- next.delete("modeler");
65
- else if (flags.modeler)
66
- next.add("modeler");
67
- if (flags["docs-mcp"])
68
- next.add("docs-mcp");
69
- return enforceComponentDependencies(next);
70
- }
71
- /**
72
- * The blueprint a non-interactive run installs: the first curated one.
73
- * Blueprints are deliberately not selectable via a CLI flag — the
74
- * wizard prompt is the only choice point.
75
- */
76
- function effectiveBlueprint(selected) {
77
- if (!selected.has("blueprint"))
78
- return undefined;
79
- return SETUP_BLUEPRINTS[0].id;
80
- }
81
- async function runPrerequisites(ctx) {
82
- const results = await checkPrerequisites();
83
- for (const result of results) {
84
- ctx.logger.info(` ${result.ok ? "✓" : "✗"} ${result.title}: ${result.detail}`);
85
- }
86
- const failed = results.filter((result) => !result.ok);
87
- if (failed.length > 0) {
88
- throw new Error([
89
- ...failed.map((result) => `${result.title}: ${result.detail}${result.hint ? ` ${result.hint}` : ""}`),
90
- "To set up Camunda by hand instead:",
91
- ...MANUAL_SETUP_LINKS.map((link) => `${link.label}: ${link.url}`),
92
- ].join("\n"));
93
- }
94
- }
95
- /** The CLI's own entry point, for self-invoking plugin commands. */
96
- const CLI_ENTRY = realpathSync(resolve(import.meta.dirname, `../index${extname(import.meta.filename)}`));
97
- /**
98
- * The cluster command lives in the built-in cluster plugin, which owns
99
- * process exit on failure — so setup runs it as a child process and maps
100
- * the exit code onto the step result. `cluster start` downloads Camunda 8
101
- * Run on first run, so this one step covers install and start.
102
- *
103
- * The child's stdout is streamed through a line filter that drops the
104
- * download progress lines (`//> 42% …`) and feeds the step's output
105
- * buffer (via ctx.logger) — it surfaces only when the step fails.
106
- * stderr passes through immediately: the plugin's warnings and failure
107
- * diagnostics are actionable either way. The child is pinned to text
108
- * mode so its lines stay plain and filterable no matter the session's
109
- * output mode.
110
- */
111
- function spawnClusterStart(ctx) {
112
- return new Promise((resolvePromise, rejectPromise) => {
113
- const child = spawn(process.execPath, [CLI_ENTRY, "cluster", "start"], {
114
- stdio: ["ignore", "pipe", "pipe"],
115
- env: { ...process.env, C8CTL_OUTPUT_MODE: "text" },
116
- });
117
- const forward = (stream, essential) => createLineForwarder({
118
- write: (line) => ctx.logger.info(line, { stream, essential }),
119
- skip: isClusterProgressLine,
120
- });
121
- const out = forward("stdout", false);
122
- const err = forward("stderr", true);
123
- child.stdout?.setEncoding("utf-8");
124
- child.stderr?.setEncoding("utf-8");
125
- child.stdout?.on("data", (chunk) => out.push(chunk));
126
- child.stderr?.on("data", (chunk) => err.push(chunk));
127
- child.on("error", (error) => rejectPromise(new Error(`Could not run c8ctl cluster start: ${error.message}`)));
128
- child.on("close", (code) => {
129
- out.flush();
130
- err.flush();
131
- if (code === 0) {
132
- resolvePromise();
133
- }
134
- else {
135
- rejectPromise(new Error(`c8ctl cluster start failed (exit code ${code}).`));
136
- }
137
- });
138
- });
139
- }
140
- function spawnClusterStop(ctx) {
141
- return new Promise((resolvePromise, rejectPromise) => {
142
- const child = spawn(process.execPath, [CLI_ENTRY, "cluster", "stop"], {
143
- stdio: ["ignore", "pipe", "pipe"],
144
- env: { ...process.env, C8CTL_OUTPUT_MODE: "text" },
145
- });
146
- const forward = (stream) => createLineForwarder({
147
- write: (line) => ctx.logger.info(line, { stream, essential: true }),
148
- skip: () => false,
149
- });
150
- const out = forward("stdout");
151
- const err = forward("stderr");
152
- child.stdout?.setEncoding("utf-8");
153
- child.stderr?.setEncoding("utf-8");
154
- child.stdout?.on("data", (chunk) => out.push(chunk));
155
- child.stderr?.on("data", (chunk) => err.push(chunk));
156
- child.on("error", (error) => rejectPromise(new Error(`Could not run c8ctl cluster stop: ${error.message}`)));
157
- child.on("close", (code) => {
158
- out.flush();
159
- err.flush();
160
- if (code === 0) {
161
- resolvePromise();
162
- }
163
- else {
164
- rejectPromise(new Error(`c8ctl cluster stop failed (exit code ${code}).`));
165
- }
166
- });
167
- });
168
- }
169
- /** c8run's launcher exits before the services report healthy — poll for it. */
170
- const CLUSTER_HEALTH_TIMEOUT_MS = 120_000;
171
- const CLUSTER_HEALTH_POLL_MS = 2_000;
172
- async function runClusterStart(ctx, run) {
173
- await spawnClusterStart(ctx);
174
- const deadline = Date.now() + CLUSTER_HEALTH_TIMEOUT_MS;
175
- for (;;) {
176
- const health = await checkLocalClusterHealth();
177
- if (health.healthy) {
178
- run.clusterStarted = true;
179
- return;
180
- }
181
- if (Date.now() >= deadline) {
182
- throw new Error(`The cluster did not become healthy within ${CLUSTER_HEALTH_TIMEOUT_MS / 1000}s (${health.detail}). Check: c8ctl cluster status`);
183
- }
184
- ctx.logger.info(" Waiting for the cluster to become healthy…");
185
- await new Promise((resolveWait) => setTimeout(resolveWait, CLUSTER_HEALTH_POLL_MS));
186
- }
187
- }
188
- async function runModelerInstall(ctx) {
189
- // Always quiet: the installer's progress chatter is noise next to the
190
- // step report — the step's status line is the signal. Failures still
191
- // throw with diagnostics.
192
- await installDesktopModeler({
193
- isDryRun: false,
194
- logger: ctx.logger,
195
- quiet: true,
196
- });
197
- }
198
- async function runBlueprintScaffold(ctx, run) {
199
- const id = run.blueprintId ?? SETUP_BLUEPRINTS[0].id;
200
- const scaffolded = await scaffoldSetupBlueprint({
201
- id,
202
- // The completion line is the step's takeaway — fresh or reused —
203
- // so it survives the success collapse; progress chatter does not.
204
- onProgress: (event) => ctx.logger.info(event.message, {
205
- essential: event.phase === "complete",
206
- }),
207
- });
208
- run.blueprintDir = scaffolded.directory;
209
- }
210
- async function runBlueprintDeploy(ctx, run) {
211
- const { logger } = ctx;
212
- const blueprint = setupBlueprintById(run.blueprintId ?? SETUP_BLUEPRINTS[0].id);
213
- const directory = run.blueprintDir;
214
- if (!directory) {
215
- throw new Error("The blueprint project was not created.");
216
- }
217
- const deployDir = join(directory, blueprint.deployPath ?? ".");
218
- // The cluster was started moments ago; re-check so a cluster that
219
- // died in between gets a next action instead of a connection dump.
220
- const health = await checkLocalClusterHealth();
221
- if (!health.healthy) {
222
- throw new Error([
223
- `Could not reach the local cluster (${health.detail}).`,
224
- "Start it with: c8ctl cluster start",
225
- // Pin the same local profile the healthy path deploys to, so the
226
- // recovery cannot land on a remote cluster from the session or env.
227
- `Then deploy the project with: c8ctl deploy "${deployDir}" --profile local`,
228
- ].join("\n"));
229
- }
230
- // Both mutations target the cluster the health check just probed: the
231
- // built-in local profile and its default tenant. An explicit profile
232
- // and tenant win over the session and CAMUNDA_* env vars, so neither
233
- // a remote active profile nor a preselected tenant can redirect the
234
- // first-run deployment.
235
- await deployResources([deployDir], {
236
- profile: DEFAULT_PROFILE,
237
- basePath: directory,
238
- verbose: ctx.verbose,
239
- tenantId: LOCAL_TENANT_ID,
240
- // The step report is the signal; its progress render is noise here.
241
- // The step's buffered logger routes failure diagnostics through the
242
- // title-closing hook instead of colliding with the open title line.
243
- quiet: true,
244
- suppressSkippedLog: true,
245
- logger: ctx.logger,
246
- });
247
- const processFile = join(directory, blueprint.processFile);
248
- const processId = extractProcessId(readFileSync(processFile, "utf-8"));
249
- if (!processId) {
250
- throw new Error(`Could not find a process id in ${blueprint.processFile}.`);
251
- }
252
- logger.info(`Starting a ${blueprint.name} process instance...`);
253
- const created = await createClient(DEFAULT_PROFILE).createProcessInstance({
254
- processDefinitionId: ProcessDefinitionId.assumeExists(processId),
255
- tenantId: TenantId.assumeExists(LOCAL_TENANT_ID),
256
- ...(blueprint.startVariables !== undefined && {
257
- variables: blueprint.startVariables,
258
- }),
259
- });
260
- logger.info(`Process instance created: ${created.processInstanceKey}`);
261
- run.instanceStarted = true;
262
- }
263
- const NO_HARNESS_HINT = "Install Claude Code, GitHub Copilot CLI or Cursor, then re-run c8ctl setup.";
264
- async function runSkillsInstall(ctx) {
265
- const harnesses = detectInstalledHarnesses();
266
- if (harnesses.length === 0) {
267
- ctx.logger.info(`No supported AI coding harness detected — nothing to install into. ${NO_HARNESS_HINT}`, { essential: true });
268
- return;
269
- }
270
- for (const harness of harnesses) {
271
- ctx.logger.info(`Checking Camunda skills (${CAMUNDA_SKILLS_REPOSITORY}) for ${harness}…`, { essential: true });
272
- await runSkillInstall(harness);
273
- }
274
- }
275
- function runMcpInstall(docs) {
276
- return (ctx) => {
277
- const plans = planMcpConfigs({
278
- requested: [],
279
- operation: "install",
280
- docs,
281
- orchestration: !docs,
282
- alias: "camunda",
283
- connection: docs ? undefined : buildMcpConnection(DEFAULT_PROFILE),
284
- });
285
- for (const plan of plans) {
286
- writeMcpConfig(plan);
287
- ctx.logger.info(`MCP configuration: ${plan.harness} (${plan.path})`, {
288
- essential: true,
289
- });
290
- }
291
- if (docs) {
292
- ctx.logger.info("The docs server asks you to sign in in a browser on first use.", {
293
- essential: true,
294
- });
295
- }
296
- };
297
- }
298
- /** planMcpConfigs throws this when the machine has no known harness. */
299
- function isNoHarnessError(error) {
300
- return (error instanceof Error &&
301
- error.message.startsWith("No supported MCP harness was detected"));
302
- }
303
- function guardedMcpInstall(docs) {
304
- const executor = runMcpInstall(docs);
305
- return async (ctx, run) => {
306
- try {
307
- await executor(ctx, run);
308
- }
309
- catch (error) {
310
- if (isNoHarnessError(error)) {
311
- ctx.logger.info(`No supported AI coding harness detected — nothing to configure. ${NO_HARNESS_HINT}`, { essential: true });
312
- return;
313
- }
314
- throw error;
315
- }
316
- };
317
- }
318
- const STEP_EXECUTORS = {
319
- prerequisites: runPrerequisites,
320
- "start-cluster": runClusterStart,
321
- "install-modeler": runModelerInstall,
322
- "scaffold-blueprint": runBlueprintScaffold,
323
- "deploy-blueprint": runBlueprintDeploy,
324
- "install-skills": runSkillsInstall,
325
- "cluster-mcp": guardedMcpInstall(false),
326
- "docs-mcp": guardedMcpInstall(true),
327
- };
328
- /**
329
- * A ctx whose logger buffers non-essential info output: on success the
330
- * buffer is dropped and the step collapses to its status line; on
331
- * failure the buffer is flushed above the error. Essential lines,
332
- * warnings and errors pass through wrapped in `aroundPassthrough`, so
333
- * the step's title line closes before they print and — except for
334
- * errors, which precede a failing step's diagnostics — reopens after.
335
- */
336
- function withBufferedOutput(ctx, buffer, aroundPassthrough) {
337
- const { logger } = ctx;
338
- const bufferedLogger = Object.create(logger, {
339
- info: {
340
- value: (message, options) => {
341
- if (options?.essential) {
342
- aroundPassthrough(() => logger.info(message, options));
343
- }
344
- else {
345
- buffer.push({ message, stream: options?.stream });
346
- }
347
- },
348
- },
349
- warn: {
350
- value: (message) => {
351
- aroundPassthrough(() => logger.warn(message));
352
- },
353
- },
354
- error: {
355
- value: (message, error) => {
356
- // A step that logs an error is failing, and its diagnostics
357
- // may follow outside the wrapped logger (deploy-helpers
358
- // writes them straight to stderr) — close the title for
359
- // good instead of stranding a reopened frame among them.
360
- aroundPassthrough(() => logger.error(message, error), {
361
- resume: false,
362
- });
363
- },
364
- },
365
- success: {
366
- value: (message, key) => {
367
- aroundPassthrough(() => logger.success(message, key));
368
- },
369
- },
370
- });
371
- return { ...ctx, logger: bufferedLogger };
372
- }
373
- /**
374
- * Run every selected step in plan order. Each step announces its title
375
- * and the status tag completes the same line — unless the step printed
376
- * essential output in between, in which case the status gets its own
377
- * line. Step output is buffered and shown only when the step fails,
378
- * followed by the error. Steps whose dependencies did not succeed are
379
- * skipped with the unmet steps named. Returns the failed-step count and
380
- * the state steps handed along (e.g. the scaffolded project directory).
381
- */
382
- async function executePlan(ctx, selected, blueprintId, { color }) {
383
- const { logger } = ctx;
384
- const run = { blueprintId };
385
- const succeeded = new Set();
386
- let failures = 0;
387
- const width = Math.max(...SETUP_STEPS.map((step) => step.title.length));
388
- for (const step of SETUP_STEPS) {
389
- if (step.component !== null && !selected.has(step.component))
390
- continue;
391
- const unmet = (step.dependsOn ?? []).filter((dep) => !succeeded.has(dep));
392
- // A clean-run step (the deploy finale) also waits for every earlier
393
- // step to have succeeded — no first process on a broken setup.
394
- const needsCleanRun = step.requiresCleanRun === true && failures > 0;
395
- if (unmet.length > 0 || needsCleanRun) {
396
- logger.info(formatStepResult(step.title, "skipped", width, { color }), {
397
- essential: true,
398
- });
399
- const names = unmet
400
- .map((dep) => SETUP_STEPS.find((s) => s.id === dep)?.title ?? dep)
401
- .join(", ");
402
- logger.info(unmet.length > 0
403
- ? ` needs: ${names}`
404
- : " needs: all previous steps to succeed", { essential: true });
405
- continue;
406
- }
407
- // The title line stays open: the status tag completes it. Essential
408
- // step output closes it first, so it never garbles mid-line — and
409
- // on a terminal the line reopens below the printed output with a
410
- // fresh spinner, so a chatty long step (the skills install prints
411
- // one line per harness, then downloads) keeps its activity
412
- // indicator. Piped and --quiet runs keep the plain, static line.
413
- let titleOpen = false;
414
- let spinner = null;
415
- let stepActive = true;
416
- // Animate only when the spinning line fits the terminal: a wrapped
417
- // line would redraw on its continuation row, adding rows instead
418
- // of spinning in place.
419
- const canAnimate = color &&
420
- step.title.length + 4 <=
421
- (process.stdout.columns ?? Number.POSITIVE_INFINITY);
422
- const openTitle = () => {
423
- process.stdout.write(` ${step.title}`);
424
- titleOpen = true;
425
- if (canAnimate) {
426
- spinner = startStepSpinner({
427
- title: step.title,
428
- write: (text) => process.stdout.write(text),
429
- });
430
- }
431
- };
432
- if (!ctx.quiet)
433
- openTitle();
434
- // Returns true when a spinning line was closed — the passthrough
435
- // wrapper then reopens it after the essential output, below what
436
- // was printed.
437
- const closeTitle = () => {
438
- if (!titleOpen)
439
- return false;
440
- const hadSpinner = spinner !== null;
441
- spinner?.stop();
442
- spinner = null;
443
- // With a spinner the line ends in a frame glyph and this rewrite
444
- // is shorter — erase to end of line so the glyph doesn't linger.
445
- process.stdout.write(hadSpinner ? `\r ${step.title}\x1b[K\n` : "\n");
446
- titleOpen = false;
447
- return hadSpinner;
448
- };
449
- const aroundPassthrough = (emit, { resume = true } = {}) => {
450
- const reopen = closeTitle();
451
- emit();
452
- if (reopen && resume && stepActive)
453
- openTitle();
454
- };
455
- const reportStatus = (status) => {
456
- stepActive = false;
457
- if (titleOpen) {
458
- spinner?.stop();
459
- const suffix = formatStepStatusSuffix(step.title, status, width, {
460
- color,
461
- });
462
- process.stdout.write(spinner ? `\r ${step.title}${suffix}\n` : `${suffix}\n`);
463
- titleOpen = false;
464
- }
465
- else {
466
- logger.info(formatStepResult(step.title, status, width, { color }), {
467
- essential: true,
468
- });
469
- }
470
- };
471
- const buffered = [];
472
- try {
473
- await STEP_EXECUTORS[step.id](withBufferedOutput(ctx, buffered, aroundPassthrough), run);
474
- succeeded.add(step.id);
475
- reportStatus("success");
476
- }
477
- catch (error) {
478
- failures += 1;
479
- reportStatus("error");
480
- // The step failed — its buffered progress is now the diagnostics.
481
- for (const line of buffered) {
482
- logger.info(` ${line.message}`, {
483
- stream: line.stream,
484
- essential: true,
485
- });
486
- }
487
- // A SilentError was already rendered in full by its helper
488
- // (e.g. the deploy diagnostics) — don't print the summary again.
489
- if (!(error instanceof SilentError)) {
490
- const message = error instanceof Error ? error.message : String(error);
491
- for (const line of message.split("\n")) {
492
- logger.info(` ${line}`, { essential: true });
493
- }
494
- }
495
- // Errors may carry a recovery hint (e.g. scaffold errors) — the
496
- // message alone is not actionable without it.
497
- const hint = error instanceof Error &&
498
- "hint" in error &&
499
- typeof error.hint === "string"
500
- ? error.hint
501
- : undefined;
502
- if (hint) {
503
- for (const line of hint.split("\n")) {
504
- logger.info(` ${line}`, { essential: true });
505
- }
506
- }
507
- }
508
- }
509
- return { failures, run };
510
- }
511
- function setupRemovalPreview(inventory, stopCluster) {
512
- const items = [];
513
- const warnings = [];
514
- const lines = ["Setup removal preview:"];
515
- for (const { plan, servers, preservedServers } of inventory.mcp) {
516
- for (const server of servers) {
517
- items.push({
518
- type: "mcp-server",
519
- harness: plan.harness,
520
- server,
521
- path: plan.path,
522
- });
523
- lines.push(` Remove MCP server "${server}" for ${plan.harness} from ${plan.path}`);
524
- }
525
- for (const server of preservedServers) {
526
- const warning = `Preserved foreign MCP server "${server}" for ${plan.harness} in ${plan.path}; it does not match setup-managed configuration.`;
527
- warnings.push(warning);
528
- lines.push(` ${warning}`);
529
- }
530
- }
531
- for (const failure of inventory.mcpPlanningFailures) {
532
- const warning = `Could not inspect MCP configuration for ${failure.harness}: ${failure.message}. That configuration was left untouched.`;
533
- warnings.push(warning);
534
- lines.push(` Warning: ${warning}`);
535
- }
536
- for (const failure of inventory.skillDiscoveryFailures) {
537
- const warning = `Could not inspect Camunda skills for ${failure.harness}: ${failure.message}. Those skills were left untouched.`;
538
- warnings.push(warning);
539
- lines.push(` Warning: ${warning}`);
540
- }
541
- for (const failure of inventory.blueprintPlanningFailures) {
542
- const warning = `Could not inspect setup blueprint marker in ${failure.directory}: ${failure.message}. That project was left untouched.`;
543
- warnings.push(warning);
544
- lines.push(` Warning: ${warning}`);
545
- }
546
- for (const skill of inventory.skills) {
547
- items.push({
548
- type: "skill",
549
- harness: skill.harness,
550
- name: skill.name,
551
- path: skill.path,
552
- });
553
- lines.push(` Remove Camunda skill "${skill.name}" for ${skill.harness} (${skill.path}; all contents will be removed)`);
554
- }
555
- for (const blueprint of inventory.blueprints) {
556
- const files = [...new Set([...blueprint.files, ".c8ctl-blueprint.json"])];
557
- items.push({
558
- type: "blueprint",
559
- id: blueprint.blueprint.id,
560
- name: blueprint.blueprint.name,
561
- directory: blueprint.directory,
562
- files,
563
- });
564
- lines.push(` Remove ${blueprint.blueprint.name} blueprint files from ${blueprint.directory}:`);
565
- for (const file of files)
566
- lines.push(` ${file}`);
567
- }
568
- if (stopCluster) {
569
- items.push({ type: "local-cluster", action: "stop" });
570
- lines.push(" Stop the local cluster with `c8ctl cluster stop` (downloaded binaries and runtime data will be kept)");
571
- }
572
- if (items.length === 0)
573
- lines.push(" No setup-managed components were found.");
574
- lines.push(" Listed skill directories and blueprint files may contain local edits; those contents will be removed. Untracked blueprint files and Desktop Modeler are not removed.");
575
- lines.push("Nothing was removed.");
576
- return {
577
- text: lines.join("\n"),
578
- payload: {
579
- command: "setup",
580
- action: "remove",
581
- preview: true,
582
- items,
583
- ...(warnings.length > 0 ? { warnings } : {}),
584
- },
585
- };
586
- }
587
- function removalFailure(ctx, action, error) {
588
- const message = error instanceof Error ? error.message : String(error);
589
- ctx.logger.error(`Could not ${action}: ${message}`);
590
- }
591
- async function applySetupRemoval(ctx, inventory, stopCluster) {
592
- const { logger } = ctx;
593
- let failures = inventory.mcpPlanningFailures.length +
594
- inventory.skillDiscoveryFailures.length +
595
- inventory.blueprintPlanningFailures.length;
596
- for (const failure of inventory.mcpPlanningFailures) {
597
- logger.error(`Could not inspect MCP configuration for ${failure.harness}: ${failure.message}. That configuration was left untouched.`);
598
- }
599
- for (const failure of inventory.skillDiscoveryFailures) {
600
- logger.error(`Could not inspect Camunda skills for ${failure.harness}: ${failure.message}. Those skills were left untouched.`);
601
- }
602
- for (const failure of inventory.blueprintPlanningFailures) {
603
- logger.error(`Could not inspect setup blueprint marker in ${failure.directory}: ${failure.message}. That project was left untouched.`);
604
- }
605
- if (stopCluster) {
606
- try {
607
- await spawnClusterStop(ctx);
608
- logger.info("Stopped the local cluster; downloaded binaries and runtime data were kept.", { essential: true });
609
- }
610
- catch (error) {
611
- failures += 1;
612
- removalFailure(ctx, "stop the local cluster", error);
613
- }
614
- }
615
- for (const { plan, servers } of inventory.mcp) {
616
- try {
617
- writeMcpConfig(plan);
618
- for (const server of servers) {
619
- logger.info(`Removed MCP server "${server}" for ${plan.harness} from ${plan.path}.`, { essential: true });
620
- }
621
- }
622
- catch (error) {
623
- failures += 1;
624
- removalFailure(ctx, `remove MCP configuration for ${plan.harness} (${plan.path})`, error);
625
- }
626
- }
627
- for (const skill of inventory.skills) {
628
- try {
629
- removeCamundaSkill(skill);
630
- logger.info(`Removed Camunda skill "${skill.name}" for ${skill.harness} (${skill.path}).`, { essential: true });
631
- }
632
- catch (error) {
633
- failures += 1;
634
- removalFailure(ctx, `remove Camunda skill "${skill.name}" for ${skill.harness}`, error);
635
- }
636
- }
637
- for (const blueprint of inventory.blueprints) {
638
- try {
639
- const result = removeSetupBlueprint(blueprint);
640
- if (result.remainingFiles.length > 0) {
641
- throw new Error(`Marker-listed files could not be removed: ${result.remainingFiles.join(", ")}.`);
642
- }
643
- logger.info(`Removed ${blueprint.blueprint.name} blueprint files from ${blueprint.directory}.`, { essential: true });
644
- if (result.directoryExists) {
645
- const message = resolve(blueprint.directory) === resolve(process.cwd())
646
- ? `Kept ${blueprint.directory} because it is the current working directory.`
647
- : `Kept untracked files in ${blueprint.directory}; remove them manually if desired.`;
648
- logger.info(message, { essential: true });
649
- }
650
- }
651
- catch (error) {
652
- failures += 1;
653
- removalFailure(ctx, `remove the ${blueprint.blueprint.name} blueprint from ${blueprint.directory}`, error);
654
- }
655
- }
656
- if (failures > 0) {
657
- process.exitCode = 1;
658
- logger.info(`Setup removal finished with ${failures} failed action(s).`, {
659
- essential: true,
660
- });
661
- }
662
- else {
663
- logger.info("Setup removal finished.", { essential: true });
664
- }
665
- }
666
- async function runSetupRemoval(ctx, stopCluster) {
667
- const { logger } = ctx;
668
- const inventory = await inspectSetupRemovalInventory();
669
- const preview = setupRemovalPreview(inventory, stopCluster);
670
- const jsonMode = logger.mode === "json";
671
- if (ctx.isDryRun || jsonMode) {
672
- logger.json({
673
- ...(ctx.isDryRun ? { dryRun: true } : {}),
674
- ...preview.payload,
675
- });
676
- return;
677
- }
678
- logger.output(preview.text);
679
- if (preview.payload.items.length === 0) {
680
- if (inventory.mcpPlanningFailures.length > 0 ||
681
- inventory.skillDiscoveryFailures.length > 0 ||
682
- inventory.blueprintPlanningFailures.length > 0) {
683
- process.exitCode = 1;
684
- }
685
- return;
686
- }
687
- const interactive = !ctx.quiet && isInteractive() && !ctx.yes;
688
- if (interactive) {
689
- const confirmation = await select({
690
- message: "Remove the listed setup components?",
691
- options: [
692
- { label: "Keep these components", value: false },
693
- { label: "Remove the listed components", value: true },
694
- ],
695
- });
696
- if (confirmation.cancelled || !confirmation.value) {
697
- logger.info("Cancelled — nothing was removed.", { essential: true });
698
- return;
699
- }
700
- }
701
- else if (!ctx.yes) {
702
- const command = [
703
- "c8ctl",
704
- "setup",
705
- "--remove",
706
- ...(stopCluster ? ["--stop-cluster"] : []),
707
- "--yes",
708
- ].join(" ");
709
- logger.info(`Nothing was removed. Run "${command}" to confirm.`, {
710
- essential: true,
711
- });
712
- return;
713
- }
714
- await applySetupRemoval(ctx, inventory, stopCluster);
715
- }
716
- // ── The command ────────────────────────────────────────────────────
717
- export const setupCommand = defineCommand("setup", "", async (ctx, flags) => {
718
- const { logger } = ctx;
719
- if (flags["stop-cluster"] && !flags.remove) {
720
- throw new Error("--stop-cluster can only be used with --remove.");
721
- }
722
- if (flags.remove) {
723
- if (flags.modeler || flags["no-modeler"] || flags["docs-mcp"]) {
724
- throw new Error("--remove cannot be combined with --modeler, --no-modeler, or --docs-mcp.");
725
- }
726
- await runSetupRemoval(ctx, flags["stop-cluster"] === true);
727
- return { kind: "none" };
728
- }
729
- // Custom dry-run payload: setup performs local installs, not one API call.
730
- if (ctx.isDryRun) {
731
- const selected = applyComponentFlags(defaultSelection(), flags);
732
- logger.json({
733
- dryRun: true,
734
- ...setupPlanPayload(selected, {
735
- blueprint: effectiveBlueprint(selected),
736
- }),
737
- });
738
- return { kind: "none" };
739
- }
740
- const jsonMode = logger.mode === "json";
741
- // JSON mode never prompts: the plan payload must not block on a TTY menu.
742
- const interactive = !jsonMode && isInteractive() && !ctx.yes && !ctx.quiet;
743
- // The step report goes to stdout — color its status tags only when
744
- // stdout is a terminal, so piped output stays plain text.
745
- const color = process.stdout.isTTY === true;
746
- // The banner is UI chrome: hidden by --quiet, omitted in JSON mode.
747
- if (!jsonMode && !ctx.quiet) {
748
- const banner = renderWelcomeBanner({ color: interactive });
749
- if (interactive) {
750
- process.stderr.write(`${banner}\n`);
751
- }
752
- else {
753
- logger.output(banner);
754
- }
755
- }
756
- let selected;
757
- if (interactive) {
758
- const result = await multiSelect({
759
- message: "What should we set up for you?",
760
- options: SETUP_COMPONENTS.map((c) => ({
761
- label: c.label,
762
- description: c.why,
763
- value: c.id,
764
- checked: c.defaultSelected,
765
- group: c.group,
766
- requires: c.requires?.map((r) => ({ value: r.id, reason: r.reason })),
767
- })),
768
- });
769
- if (result.cancelled) {
770
- logger.info("Cancelled — nothing was changed.");
771
- return { kind: "none" };
772
- }
773
- selected = new Set(result.values);
774
- }
775
- else {
776
- selected = defaultSelection();
777
- }
778
- selected = applyComponentFlags(selected, flags);
779
- // Every question comes before any work: pick the blueprint next.
780
- let blueprintId = effectiveBlueprint(selected);
781
- if (selected.has("blueprint") && interactive) {
782
- const choice = await select({
783
- message: "Which starter blueprint should we install?",
784
- options: SETUP_BLUEPRINTS.map((b) => ({
785
- label: b.name,
786
- description: `${b.description} — guide: ${b.guideUrl}`,
787
- value: b.id,
788
- })),
789
- });
790
- if (choice.cancelled) {
791
- logger.info("Cancelled — nothing was changed.");
792
- return { kind: "none" };
793
- }
794
- blueprintId = choice.value;
795
- }
796
- if (jsonMode) {
797
- logger.json(setupPlanPayload(selected, { blueprint: blueprintId }));
798
- return { kind: "none" };
799
- }
800
- // Without an interactive selection or --yes there is no go-ahead:
801
- // stop before any work, so a piped run never installs anything.
802
- if (!interactive && !ctx.yes) {
803
- logger.info('Nothing was installed. Run "c8ctl setup --yes" to set everything up, or run interactively to choose what gets installed.');
804
- return { kind: "none" };
805
- }
806
- // No surprise browser windows: the docs MCP sign-in opens one when
807
- // the assistant first connects, so say so before the first step runs.
808
- // (The cluster start opens Operate the same way a plain "c8ctl
809
- // cluster start" does.)
810
- if (selected.has("docs-mcp")) {
811
- logger.info("Heads up: the docs MCP server needs you to sign in — your AI assistant will open a browser window for it when it connects.", { essential: true });
812
- }
813
- const { failures, run } = await executePlan(ctx, selected, blueprintId, {
814
- color,
815
- });
816
- // The takeaway of the whole run, boxed so it stands apart from the
817
- // step report above it. A blueprint owns its actionable lines (what
818
- // the run left behind, what to do with it); without one but with a
819
- // running cluster, point at the first process run instead.
820
- const nextSteps = [];
821
- if (run.blueprintDir) {
822
- const blueprint = setupBlueprintById(run.blueprintId ?? SETUP_BLUEPRINTS[0].id);
823
- // Outcome lines describe the started instance — claim them only
824
- // when the deploy step actually started one. On a failed deploy
825
- // the Project/Guide references below still apply.
826
- if (run.instanceStarted) {
827
- nextSteps.push(...blueprint.nextSteps(run.blueprintDir));
828
- }
829
- nextSteps.push(`Project: ${run.blueprintDir}`);
830
- nextSteps.push(`Guide: ${blueprint.guideUrl}`);
831
- }
832
- else if (run.clusterStarted) {
833
- // Both suggestions pin the local profile and its <default> tenant —
834
- // the session's active profile and tenant may point at a remote
835
- // cluster. Two lines: && is a syntax error in Windows
836
- // PowerShell 5.1.
837
- nextSteps.push("Run your first process:");
838
- nextSteps.push(' c8ctl use tenant "<default>"');
839
- nextSteps.push(" c8ctl run my-process.bpmn --profile local");
840
- nextSteps.push('Or re-run "c8ctl setup" and pick a starter blueprint.');
841
- }
842
- if (run.clusterStarted) {
843
- nextSteps.push("Operate: http://localhost:8080/operate (demo/demo)");
844
- }
845
- if (nextSteps.length > 0) {
846
- logger.info(`\n${renderNextSteps(nextSteps, { color, maxWidth: process.stdout.columns || undefined })}`, { essential: true });
847
- }
848
- if (failures > 0) {
849
- logger.info(`Setup finished with ${failures} failed step(s). Fix the cause and re-run c8ctl setup — finished work is picked up, not repeated.`, { essential: true });
850
- process.exitCode = 1;
851
- return { kind: "none" };
852
- }
853
- logger.success("Setup finished.");
854
- return { kind: "none" };
855
- });
856
- //# sourceMappingURL=setup.js.map