@agimon-ai/po-workflow 0.0.0-alpha.13 → 0.0.0-alpha.130

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 (50) hide show
  1. package/LICENSE +149 -29
  2. package/README.md +175 -17
  3. package/dist/RecoverWorkflowService-C60pnmub.mjs +13701 -0
  4. package/dist/RecoverWorkflowService-C60pnmub.mjs.map +1 -0
  5. package/dist/RecoverWorkflowService-DJ9dzZmJ.cjs +14046 -0
  6. package/dist/RecoverWorkflowService-DJ9dzZmJ.cjs.map +1 -0
  7. package/dist/apiContracts.cjs +197 -35
  8. package/dist/apiContracts.cjs.map +1 -1
  9. package/dist/apiContracts.d.mts.map +1 -1
  10. package/dist/apiContracts.mjs +197 -35
  11. package/dist/apiContracts.mjs.map +1 -1
  12. package/dist/cli.cjs +1153 -0
  13. package/dist/cli.cjs.map +1 -0
  14. package/dist/cli.d.mts +1 -0
  15. package/dist/cli.mjs +1154 -0
  16. package/dist/cli.mjs.map +1 -0
  17. package/dist/extensions/native.mjs +3757 -686
  18. package/dist/extensions/native.mjs.map +1 -1
  19. package/dist/extensions/server.cjs +7756 -2945
  20. package/dist/extensions/server.cjs.map +1 -1
  21. package/dist/extensions/server.d.mts +2 -2
  22. package/dist/extensions/server.d.mts.map +1 -1
  23. package/dist/extensions/server.mjs +7750 -2916
  24. package/dist/extensions/server.mjs.map +1 -1
  25. package/dist/extensions/web.mjs +4451 -2829
  26. package/dist/extensions/web.mjs.map +1 -1
  27. package/dist/index.cjs +3 -1
  28. package/dist/index.d.mts +72 -4
  29. package/dist/index.d.mts.map +1 -1
  30. package/dist/index.mjs +3 -1
  31. package/dist/rolldown-runtime-VH7oDXx4.cjs +28 -0
  32. package/dist/workflowCommandTemplate-r57z3b46.mjs +79 -0
  33. package/dist/workflowCommandTemplate-r57z3b46.mjs.map +1 -0
  34. package/dist/workflowCommandTemplate-w6rOCJpw.cjs +102 -0
  35. package/dist/workflowCommandTemplate-w6rOCJpw.cjs.map +1 -0
  36. package/dist/{workflowLaunchCommand-C69Nn3k5.cjs → workflowLaunchCommand-Cm2_aoJ3.cjs} +21 -5
  37. package/dist/workflowLaunchCommand-Cm2_aoJ3.cjs.map +1 -0
  38. package/dist/{workflowLaunchCommand-GGqimmTC.mjs → workflowLaunchCommand-USS3q-Px.mjs} +21 -5
  39. package/dist/workflowLaunchCommand-USS3q-Px.mjs.map +1 -0
  40. package/llms.txt +8 -7
  41. package/package.json +105 -25
  42. package/src/prompts/codemode-how-to-workflow/SKILL.md +175 -0
  43. package/src/prompts/help-how-to-workflow/SKILL.md +174 -0
  44. package/src/types/webWorkflows.ts +31 -1
  45. package/LICENSE.web +0 -29
  46. package/dist/workflowLaunchCommand-C69Nn3k5.cjs.map +0 -1
  47. package/dist/workflowLaunchCommand-GGqimmTC.mjs.map +0 -1
  48. package/skills/workflow-recovery/SKILL.md +0 -85
  49. package/src/prompts/po-author-workflow/SKILL.md +0 -64
  50. package/src/prompts/po-use-workflow/SKILL.md +0 -21
package/dist/cli.cjs ADDED
@@ -0,0 +1,1153 @@
1
+ #!/usr/bin/env node
2
+ const require_workflowCommandTemplate = require("./workflowCommandTemplate-w6rOCJpw.cjs");
3
+ const require_RecoverWorkflowService = require("./RecoverWorkflowService-DJ9dzZmJ.cjs");
4
+ let node_path = require("node:path");
5
+ let _agimon_ai_po_core_platform = require("@agimon-ai/po-core/platform");
6
+ let _agimon_ai_po_core_telemetry = require("@agimon-ai/po-core/telemetry");
7
+ let commander = require("commander");
8
+ let _agimon_ai_po_core_nodePlatform = require("@agimon-ai/po-core/nodePlatform");
9
+ //#region src/constants/workflowCommands.ts
10
+ const LIST_WORKFLOW_STATUSES_COMMAND_NAME = "list-workflow-statuses";
11
+ const LIST_WORKFLOW_STATUSES_COMMAND_DESCRIPTION = "List tracked workflow runs and their current stages";
12
+ const CLOSE_LAUNCHER_COMMAND_NAME = "close-launcher";
13
+ const DOCTOR_COMMAND_NAME = "doctor";
14
+ const DOCTOR_COMMAND_DESCRIPTION = "Check workflow files before running them: schema, imports, commands, runConfig keys, runners and inputs";
15
+ const RECOVER_WORKFLOW_COMMAND_NAME = "recover-workflow";
16
+ const RECOVER_WORKFLOW_COMMAND_DESCRIPTION = "Recover a failed workflow run from the local workflow registry";
17
+ const RUN_WORKFLOW_COMMAND_NAME = "run-workflow";
18
+ const RUN_WORKFLOW_COMMAND_DESCRIPTION = "Run a GitHub Actions workflow file locally on macOS";
19
+ const HOST_RUN_COMMAND_NAME = "host-run";
20
+ const STEP_COMMAND_NAME = "step";
21
+ const STEP_COMMAND_DESCRIPTION = "Record the outcome of the running workflow step (complete, fix or fail)";
22
+ const STOP_WORKFLOW_COMMAND_NAME = "stop-workflow";
23
+ const STOP_WORKFLOW_COMMAND_DESCRIPTION = "Request a running workflow to stop gracefully";
24
+ const DESCRIBE_RUN_COMMAND_NAME = "describe-run";
25
+ const DESCRIBE_RUN_COMMAND_DESCRIPTION = "Describe a workflow run directory and report declared artifact status";
26
+ const LAUNCH_PROCESS_COMMAND_NAME = "launch-process";
27
+ //#endregion
28
+ //#region src/services/WorkflowLauncherService/index.ts
29
+ const SESSION_NAME_PREFIX = "workflow-";
30
+ const MAX_SESSION_NAME_LENGTH = 80;
31
+ /**
32
+ * Multiplexer preference, most widely installed first.
33
+ *
34
+ * tmux leads because it is on most developer machines; cmux is excellent but
35
+ * niche. The previous default was cmux unconditionally, with no availability
36
+ * check anywhere, so a machine without it failed at spawn with "Unable to
37
+ * execute cmux" rather than falling back to anything.
38
+ */
39
+ const MULTIPLEXER_PREFERENCE = ["tmux", "cmux"];
40
+ function normalizeTmuxSessionName(name) {
41
+ const normalized = name.trim().replace(/[^a-zA-Z0-9_-]+/g, "-").replace(/^-+|-+$/g, "").slice(0, MAX_SESSION_NAME_LENGTH);
42
+ return `${SESSION_NAME_PREFIX}${normalized || "run"}`;
43
+ }
44
+ /** The command name the RMUX-backed native launcher re-enters this CLI with. */
45
+ const HOST_RUN_COMMAND = "host-run";
46
+ /**
47
+ * The invocation that hosts a run through bundled RMUX.
48
+ *
49
+ * The detached process keeps the compatibility socket alive while RMUX owns the
50
+ * terminal and process. The caller gets its prompt back immediately.
51
+ */
52
+ function buildNativeHostInvocation(input, cliPath, executablePath) {
53
+ return {
54
+ args: [
55
+ cliPath,
56
+ HOST_RUN_COMMAND,
57
+ "--name",
58
+ input.name,
59
+ "--cwd",
60
+ input.cwd,
61
+ "--command",
62
+ input.command
63
+ ],
64
+ command: executablePath
65
+ };
66
+ }
67
+ function buildLaunchInvocation(input) {
68
+ const launcher = input.launcher ?? "native";
69
+ if (launcher === "native") throw new Error("Native hosting is launched through buildNativeHostInvocation, which needs this CLI's own path.");
70
+ if (launcher === "tmux") {
71
+ const sessionName = normalizeTmuxSessionName(input.name);
72
+ const command = [
73
+ "export WORKFLOW_LAUNCHER_TYPE=tmux",
74
+ `export WORKFLOW_TMUX_SESSION_NAME=${require_workflowCommandTemplate.escapeShellArg(sessionName)}`,
75
+ `exec ${input.command}`
76
+ ].join("; ");
77
+ return {
78
+ args: [
79
+ "new-session",
80
+ "-d",
81
+ "-s",
82
+ sessionName,
83
+ "-c",
84
+ input.cwd,
85
+ command
86
+ ],
87
+ command: "tmux"
88
+ };
89
+ }
90
+ return {
91
+ args: [
92
+ "workspace",
93
+ "create",
94
+ "--name",
95
+ input.name,
96
+ "--cwd",
97
+ input.cwd,
98
+ "--command",
99
+ `export WORKFLOW_LAUNCHER_TYPE=cmux; exec ${input.command}`
100
+ ],
101
+ command: "cmux"
102
+ };
103
+ }
104
+ function buildCloseInvocation(input) {
105
+ return input.launcher === "tmux" ? {
106
+ args: [
107
+ "kill-session",
108
+ "-t",
109
+ input.target
110
+ ],
111
+ command: "tmux"
112
+ } : {
113
+ args: [
114
+ "close-workspace",
115
+ "--workspace",
116
+ input.target
117
+ ],
118
+ command: "cmux"
119
+ };
120
+ }
121
+ var WorkflowLauncherService = class {
122
+ runtime;
123
+ dependencies;
124
+ constructor(runtime, dependencies = {}) {
125
+ this.runtime = runtime;
126
+ this.dependencies = dependencies;
127
+ }
128
+ async launch(input) {
129
+ let launcher = input.launcher;
130
+ if (!launcher) for (const candidate of MULTIPLEXER_PREFERENCE) try {
131
+ await require_RecoverWorkflowService.workflowShellOutput(this.runtime, [
132
+ "/bin/sh",
133
+ "-c",
134
+ `command -v ${require_workflowCommandTemplate.escapeShellArg(candidate)}`
135
+ ]);
136
+ launcher = candidate;
137
+ break;
138
+ } catch {}
139
+ if (!launcher || launcher === "native") {
140
+ this.detach(buildNativeHostInvocation(input, this.dependencies.cliPath ?? this.runtime.workflowHost.cliPath, this.runtime.workflowHost.executablePath), input.cwd);
141
+ return;
142
+ }
143
+ await this.run(buildLaunchInvocation({
144
+ ...input,
145
+ launcher
146
+ }), input.cwd);
147
+ }
148
+ detach(invocation, cwd) {
149
+ const child = this.runtime.workflowHost.spawn(invocation.command, invocation.args, {
150
+ cwd,
151
+ env: this.runtime.baseEnvironment,
152
+ detached: true,
153
+ stdio: "ignore"
154
+ });
155
+ child.on("error", (error) => {
156
+ throw new Error(`Unable to execute ${invocation.command}`, { cause: error });
157
+ });
158
+ child.unref();
159
+ }
160
+ async close(input) {
161
+ await this.run(buildCloseInvocation(input));
162
+ }
163
+ async run(invocation, cwd = this.runtime.cwd) {
164
+ let result;
165
+ try {
166
+ result = (0, _agimon_ai_po_core_platform.getOrThrow)(await this.runtime.shell.exec([invocation.command, ...invocation.args], {
167
+ cwd,
168
+ env: Object.fromEntries(Object.entries(this.runtime.baseEnvironment).filter((entry) => entry[1] !== void 0)),
169
+ inheritEnv: false,
170
+ onOutput: (text, _context, info) => {
171
+ if (info.stream === "stderr") this.dependencies.writeStderr?.(text);
172
+ else this.dependencies.writeStdout?.(text);
173
+ }
174
+ }, this.runtime.ioContext));
175
+ } catch (error) {
176
+ throw new Error(`Unable to execute ${invocation.command}`, { cause: error });
177
+ }
178
+ if (result.exitCode !== 0) throw new Error(`${invocation.command} exited with status ${result.exitCode ?? "unknown"}`);
179
+ }
180
+ };
181
+ //#endregion
182
+ //#region src/bin/workflowRuntime.ts
183
+ let runtime;
184
+ let logger;
185
+ /** The standalone executable admits ambient facts once, before any engine service is constructed. */
186
+ function getCliWorkflowRuntime() {
187
+ if (runtime) return runtime;
188
+ const environment = Object.freeze({ ...process.env });
189
+ const cwd = process.cwd();
190
+ const homeDirectory = _agimon_ai_po_core_platform.nodeHost.homeDirectory();
191
+ const temporaryDirectory = _agimon_ai_po_core_platform.nodeHost.temporaryDirectory();
192
+ const execution = (0, _agimon_ai_po_core_nodePlatform.createNodePlatform)({
193
+ homeDirectory,
194
+ temporaryDirectory
195
+ }).env(cwd);
196
+ runtime = require_RecoverWorkflowService.createWorkflowRuntime({
197
+ baseEnvironment: environment,
198
+ cwd,
199
+ homeDirectory,
200
+ temporaryDirectory,
201
+ fs: execution,
202
+ shell: execution,
203
+ workflowHost: require_RecoverWorkflowService.createWorkflowHost({
204
+ environment,
205
+ cwd,
206
+ homeDirectory,
207
+ temporaryDirectory,
208
+ cliPath: require_RecoverWorkflowService.resolveWorkflowCliPath()
209
+ })
210
+ });
211
+ return runtime;
212
+ }
213
+ /** One telemetry backend per standalone CLI invocation. */
214
+ function getCliWorkflowLogger() {
215
+ return logger ??= createCliWorkflowLogger({
216
+ info: (message) => console.info(message),
217
+ warn: (message) => console.error(message),
218
+ error: (message) => console.error(message)
219
+ });
220
+ }
221
+ let installedServiceName = "workflow-mcp";
222
+ let telemetry;
223
+ function getTelemetry(serviceName) {
224
+ const runtime = getCliWorkflowRuntime();
225
+ return telemetry ??= (0, _agimon_ai_po_core_telemetry.createPoTelemetry)({
226
+ packageName: "@agimon-ai/po-workflow",
227
+ serviceName,
228
+ workspaceRoot: runtime.cwd,
229
+ cwd: runtime.cwd,
230
+ env: { ...runtime.baseEnvironment }
231
+ });
232
+ }
233
+ function createCliWorkflowLogger(baseLogger) {
234
+ return {
235
+ ...baseLogger,
236
+ async event(level, name, options = {}) {
237
+ const telemetry = getTelemetry(installedServiceName);
238
+ if (level === "error" || level === "fatal") await telemetry.recordError(name, options.exception, options.attributes);
239
+ else if (level === "warn") await telemetry.recordWarning(name, options.exception, options.attributes);
240
+ else if (level === "debug" || level === "trace") await telemetry.recordDebug(name, options.attributes);
241
+ else await telemetry.recordEvent(name, options.attributes);
242
+ },
243
+ runInSpan: (name, attributes, work, parent) => getTelemetry(installedServiceName).runInSpan(name, attributes, work, parent),
244
+ flush: flushOtelErrorLogger
245
+ };
246
+ }
247
+ async function flushOtelErrorLogger() {
248
+ await telemetry?.flush();
249
+ }
250
+ function installOtelErrorLogger(options) {
251
+ installedServiceName = options.serviceName;
252
+ getTelemetry(installedServiceName);
253
+ }
254
+ //#endregion
255
+ //#region src/bin/workflowCommands/closeLauncher.ts
256
+ function resolveLauncher(options, env) {
257
+ if (options.launcher) return options.launcher;
258
+ if (env.WORKFLOW_LAUNCHER_TYPE === "tmux") return "tmux";
259
+ if (env.CMUX_WORKSPACE_ID) return "cmux";
260
+ }
261
+ function resolveTarget(launcher, options, env) {
262
+ if (options.target) return options.target;
263
+ return launcher === "tmux" ? env.WORKFLOW_TMUX_SESSION_NAME ?? env.TMUX_PANE : env.CMUX_WORKSPACE_ID;
264
+ }
265
+ function scheduleDelayedClose(launcher, target, delaySeconds) {
266
+ const { baseEnvironment, cwd, workflowHost } = getCliWorkflowRuntime();
267
+ workflowHost.spawn(workflowHost.executablePath, [
268
+ workflowHost.cliPath,
269
+ CLOSE_LAUNCHER_COMMAND_NAME,
270
+ "--launcher",
271
+ launcher,
272
+ "--target",
273
+ target,
274
+ "--delay-seconds",
275
+ "0"
276
+ ], {
277
+ cwd,
278
+ detached: true,
279
+ env: {
280
+ ...baseEnvironment,
281
+ WORKFLOW_LAUNCHER_CLOSE_DELAY_MS: String(delaySeconds * 1e3)
282
+ },
283
+ stdio: "ignore"
284
+ }).unref();
285
+ }
286
+ async function waitForScheduledDelay(env) {
287
+ const delayMs = Number(env.WORKFLOW_LAUNCHER_CLOSE_DELAY_MS ?? 0);
288
+ if (Number.isFinite(delayMs) && delayMs > 0) await new Promise((resolve) => setTimeout(resolve, delayMs));
289
+ }
290
+ function createCloseLauncherCommand(dependencies = {}) {
291
+ const environment = dependencies.environment ?? (() => getCliWorkflowRuntime().baseEnvironment);
292
+ const createService = dependencies.createService ?? (() => new WorkflowLauncherService(getCliWorkflowRuntime()));
293
+ const exit = dependencies.exit ?? ((code) => process.exit(code));
294
+ const launchDelayedClose = dependencies.launchDelayedClose ?? scheduleDelayedClose;
295
+ const logError = dependencies.logError ?? ((message, error) => console.error(message, error));
296
+ const logInfo = dependencies.logInfo ?? ((message) => process.stdout.write(`${message}\n`));
297
+ return new commander.Command(CLOSE_LAUNCHER_COMMAND_NAME).description("Close the launcher assigned to the current workflow process").addOption(new commander.Option("--launcher <launcher>").choices(["cmux", "tmux"])).option("--target <target>", "Explicit launcher workspace or session identity").option("--delay-seconds <seconds>", "Delay before closing the launcher", "0").action(async (options) => {
298
+ try {
299
+ const env = environment();
300
+ const launcher = resolveLauncher(options, env);
301
+ if (!launcher) {
302
+ logInfo("No managed workflow launcher identity found. Skipping close.");
303
+ return;
304
+ }
305
+ const target = resolveTarget(launcher, options, env);
306
+ if (!target) {
307
+ logInfo(`No ${launcher} target found. Skipping close.`);
308
+ return;
309
+ }
310
+ const delaySeconds = Number(options.delaySeconds);
311
+ if (!Number.isFinite(delaySeconds) || delaySeconds < 0) throw new Error(`Invalid delay: ${options.delaySeconds}`);
312
+ if (delaySeconds > 0) {
313
+ launchDelayedClose(launcher, target, delaySeconds);
314
+ logInfo(`Scheduled ${launcher} launcher ${target} to close in ${delaySeconds}s.`);
315
+ return;
316
+ }
317
+ await waitForScheduledDelay(env);
318
+ await createService().close({
319
+ launcher,
320
+ target
321
+ });
322
+ } catch (error) {
323
+ logError("Unable to close workflow launcher.", error);
324
+ exit(1);
325
+ }
326
+ });
327
+ }
328
+ const closeLauncherCommand = createCloseLauncherCommand();
329
+ //#endregion
330
+ //#region src/models/WorkflowCommandError.ts
331
+ /**
332
+ * Structured error raised by workflow CLI commands.
333
+ */
334
+ var WorkflowCommandError = class extends Error {
335
+ code;
336
+ context;
337
+ constructor(message, code, context = {}, options) {
338
+ super(message, options);
339
+ this.code = code;
340
+ this.context = context;
341
+ this.name = "WorkflowCommandError";
342
+ }
343
+ };
344
+ //#endregion
345
+ //#region src/bin/workflowCommands/controlWorkflow.ts
346
+ function createControlCommand(action, name, description) {
347
+ return new commander.Command(name).description(description).argument("<run-key>", "Running workflow run key").option("-w, --workspace <name>", "Workspace containing the running workflow", "default").requiredOption("--run-id <run-id>", "Exact running generation to control").option("-r, --reason <text>", "Optional reason to record").action(async (runKey, options) => {
348
+ try {
349
+ const registry = new require_RecoverWorkflowService.WorkflowRegistryService(getCliWorkflowRuntime());
350
+ const request = action === "pause" ? await registry.requestPause(options.workspace, runKey, options.reason, options.runId) : await registry.requestResume(options.workspace, runKey, options.runId);
351
+ process.stdout.write(`${JSON.stringify({
352
+ action,
353
+ request,
354
+ runKey,
355
+ workspace: registry.resolveWorkspace(options.workspace)
356
+ }, null, 2)}\n`);
357
+ } catch (error) {
358
+ const commandError = new WorkflowCommandError(`Error requesting workflow ${action}.`, `${action.toUpperCase()}_WORKFLOW_FAILED`, {
359
+ command: name,
360
+ runKey,
361
+ workspace: options.workspace
362
+ }, { cause: error });
363
+ console.error(`${commandError.message} [${commandError.code}]`, commandError);
364
+ process.exitCode = 1;
365
+ }
366
+ });
367
+ }
368
+ const pauseWorkflowCommand = createControlCommand("pause", "pause-workflow", "Request a running workflow to pause cooperatively.");
369
+ const resumeWorkflowCommand = createControlCommand("resume", "resume-workflow", "Resume a paused workflow.");
370
+ //#endregion
371
+ //#region src/bin/workflowCommands/describeRun.ts
372
+ const RUN_RECORD_FILENAME = "run.json";
373
+ const WORKFLOW_RUN_DIR_ENV = "WORKFLOW_RUN_DIR";
374
+ const WORKFLOW_JOB_NAME_ENV = "WORKFLOW_JOB_NAME";
375
+ const SUCCESS_EXIT_CODE$1 = 0;
376
+ const ERROR_EXIT_CODE = 1;
377
+ function createDescribeRunCommand(dependencies = {}) {
378
+ const createRegistry = dependencies.createRegistry ?? (() => new require_RecoverWorkflowService.WorkflowRegistryService(getCliWorkflowRuntime()));
379
+ const createRunDirectoryService = dependencies.createRunDirectoryService ?? (() => new require_RecoverWorkflowService.RunDirectoryService(getCliWorkflowRuntime()));
380
+ const exit = dependencies.exit ?? ((code) => process.exit(code));
381
+ const logError = dependencies.logError ?? ((message, error) => console.error(message, error));
382
+ const writeStdout = dependencies.writeStdout ?? ((message) => process.stdout.write(`${message}\n`));
383
+ return new commander.Command(DESCRIBE_RUN_COMMAND_NAME).description(DESCRIBE_RUN_COMMAND_DESCRIPTION).option("--run-dir <path>", "Workflow run directory; defaults to WORKFLOW_RUN_DIR").option("--job <name>", "Job used to classify inputs and outputs; defaults to WORKFLOW_JOB_NAME").addOption(new commander.Option("--format <format>", "Output format").choices(["text", "json"]).default("text")).action(async (options) => {
384
+ try {
385
+ const runtime = getCliWorkflowRuntime();
386
+ const env = dependencies.env ?? runtime.baseEnvironment;
387
+ const runDir = (0, node_path.resolve)(runtime.cwd, options.runDir ?? env[WORKFLOW_RUN_DIR_ENV] ?? "");
388
+ if (!options.runDir && !env[WORKFLOW_RUN_DIR_ENV]) throw new Error("--run-dir or WORKFLOW_RUN_DIR is required");
389
+ const record = await createRegistry().readRunRecord((0, node_path.resolve)(runDir, RUN_RECORD_FILENAME));
390
+ const service = createRunDirectoryService();
391
+ const inspection = await service.inspect(runDir, record.runDirectory, { jobName: options.job ?? env[WORKFLOW_JOB_NAME_ENV] });
392
+ writeStdout(options.format === "json" ? JSON.stringify(inspection, null, 2) : service.formatInspection(inspection));
393
+ exit(SUCCESS_EXIT_CODE$1);
394
+ } catch (error) {
395
+ logError("Error describing workflow run.", error);
396
+ exit(ERROR_EXIT_CODE);
397
+ }
398
+ });
399
+ }
400
+ const describeRunCommand = createDescribeRunCommand();
401
+ //#endregion
402
+ //#region src/bin/workflowCommands/doctor.ts
403
+ const SUCCESS_EXIT_CODE = 0;
404
+ const FAILURE_EXIT_CODE = 1;
405
+ const KEY_SEPARATOR = ",";
406
+ function countLevel(reports, level) {
407
+ return reports.reduce((count, report) => count + report.diagnostics.filter((diagnostic) => diagnostic.level === level).length, 0);
408
+ }
409
+ function plural(count, noun) {
410
+ return `${String(count)} ${noun}${count === 1 ? "" : "s"}`;
411
+ }
412
+ /** One line per finding under its workflow, and a closing tally. */
413
+ function formatText$1(reports, cwd) {
414
+ const lines = [];
415
+ for (const report of reports) {
416
+ const errors = report.diagnostics.some((diagnostic) => diagnostic.level === "error");
417
+ lines.push(`${errors ? "fail" : "ok "} ${(0, node_path.relative)(cwd, report.path) || report.path}`);
418
+ for (const diagnostic of report.diagnostics) {
419
+ const where = diagnostic.location === void 0 ? "" : `${diagnostic.location}: `;
420
+ lines.push(` ${diagnostic.level.padEnd(7)} ${where}${diagnostic.message} [${diagnostic.code}]`);
421
+ }
422
+ }
423
+ const errors = countLevel(reports, "error");
424
+ const warnings = countLevel(reports, "warning");
425
+ lines.push(`${plural(reports.length, "workflow")}: ${plural(errors, "error")}, ${plural(warnings, "warning")}`);
426
+ return `${lines.join("\n")}\n`;
427
+ }
428
+ function createDoctorCommand(dependencies = {}) {
429
+ const cwd = dependencies.cwd ?? (() => getCliWorkflowRuntime().cwd);
430
+ const exit = dependencies.exit ?? ((code) => process.exit(code));
431
+ const writeStdout = dependencies.writeStdout ?? ((message) => process.stdout.write(message));
432
+ const writeStderr = dependencies.writeStderr ?? ((message) => process.stderr.write(message));
433
+ return new commander.Command(DOCTOR_COMMAND_NAME).description(DOCTOR_COMMAND_DESCRIPTION).argument("[paths...]", "Workflow files or directories to check", ["."]).option("--run-config-keys <keys>", "Comma-separated runConfig keys the host reads itself, such as Po's majorMode,minorModes,profile,domains,model,thinking; other keys a step's command does not read become errors").option("--strict", "Fail on warnings as well as errors").addOption(new commander.Option("--format <format>", "Output format").choices(["text", "json"]).default("text")).action(async (paths, options) => {
434
+ try {
435
+ const runConfigKeys = options.runConfigKeys?.split(KEY_SEPARATOR).map((key) => key.trim()).filter((key) => key.length > 0);
436
+ const reports = await require_RecoverWorkflowService.diagnoseWorkflows(paths, {
437
+ runtime: getCliWorkflowRuntime(),
438
+ ...runConfigKeys === void 0 ? {} : { runConfigKeys }
439
+ });
440
+ const errors = countLevel(reports, "error");
441
+ const warnings = countLevel(reports, "warning");
442
+ writeStdout(options.format === "json" ? `${JSON.stringify({
443
+ errors,
444
+ warnings,
445
+ workflows: reports
446
+ }, null, 2)}\n` : formatText$1(reports, cwd()));
447
+ exit(errors > 0 || options.strict === true && warnings > 0 ? FAILURE_EXIT_CODE : SUCCESS_EXIT_CODE);
448
+ } catch (error) {
449
+ writeStderr(`Error checking workflows: ${error instanceof Error ? error.message : String(error)}\n`);
450
+ exit(FAILURE_EXIT_CODE);
451
+ }
452
+ });
453
+ }
454
+ const doctorCommand = createDoctorCommand();
455
+ //#endregion
456
+ //#region src/bin/workflowCommands/hostRun.ts
457
+ /**
458
+ * `host-run`: own a workflow run's terminal for as long as it runs.
459
+ *
460
+ * RMUX owns the run's pseudo terminal and screen state. This detached host keeps
461
+ * the compatibility socket alive so existing cockpit clients can reach the run
462
+ * without knowing which multiplexer backs it.
463
+ *
464
+ * DESIGN PATTERNS:
465
+ * - The socket is bound before the run starts, so a reader that attaches
466
+ * immediately cannot miss the first screen
467
+ * - The child is told where its own terminal is answering, so the run record it
468
+ * writes carries the socket and a cockpit can find it later
469
+ *
470
+ * CODING STANDARDS:
471
+ * - Named exports only
472
+ * - Explicit return types on exported members
473
+ */
474
+ const SHELL = "/bin/sh";
475
+ const SHELL_COMMAND_FLAG = "-c";
476
+ const FAILED_EXIT_CODE = 1;
477
+ /** Env the run reads to record where its own terminal can be reached. */
478
+ const WORKFLOW_TERMINAL_SOCKET_ENV = "WORKFLOW_TERMINAL_SOCKET";
479
+ const WORKFLOW_LAUNCHER_TYPE_ENV = "WORKFLOW_LAUNCHER_TYPE";
480
+ const NATIVE_LAUNCHER = "native";
481
+ /**
482
+ * Hosts one run and resolves with its exit code.
483
+ *
484
+ * Exported for the same reason every other command's body is: the CLI wrapper
485
+ * is argument parsing, and the behaviour deserves a test that does not spawn a
486
+ * process.
487
+ */
488
+ async function hostWorkflowRun(options, dependencies = {}) {
489
+ const service = dependencies.createService?.() ?? new require_RecoverWorkflowService.NativeTerminalService(getCliWorkflowRuntime());
490
+ if (!await service.available()) throw new Error("Terminal hosting is unavailable: RMUX did not load. Install RMUX or use tmux or cmux instead.");
491
+ const runKey = normalizeTmuxSessionName(options.name);
492
+ const workspace = options.workspace ?? "";
493
+ const socketPath = options.socket ?? require_RecoverWorkflowService.terminalSocketPath(workspace, runKey, getCliWorkflowRuntime().temporaryDirectory);
494
+ const server = await require_RecoverWorkflowService.serveNativeTerminal(getCliWorkflowRuntime(), {
495
+ service,
496
+ runKey,
497
+ socketPath
498
+ });
499
+ try {
500
+ await service.spawn({
501
+ command: SHELL,
502
+ args: [SHELL_COMMAND_FLAG, options.command],
503
+ cwd: options.cwd,
504
+ env: {
505
+ ...process.env,
506
+ [WORKFLOW_LAUNCHER_TYPE_ENV]: NATIVE_LAUNCHER,
507
+ [WORKFLOW_TERMINAL_SOCKET_ENV]: socketPath
508
+ },
509
+ runKey
510
+ });
511
+ return await service.ended(runKey);
512
+ } finally {
513
+ await server.close();
514
+ await service.disposeAll();
515
+ }
516
+ }
517
+ function createHostRunCommand(dependencies = {}) {
518
+ const exit = dependencies.exit ?? ((code) => process.exit(code));
519
+ const logError = dependencies.logError ?? ((message, error) => console.error(message, error));
520
+ return new commander.Command(HOST_RUN_COMMAND_NAME).description("Host a workflow run through RMUX and serve its terminal on a socket").requiredOption("--name <name>", "Run display name").requiredOption("--cwd <path>", "Working directory").requiredOption("--command <command>", "Workflow command to execute").option("--workspace <workspace>", "Registry workspace the run belongs to").option("--socket <path>", "Socket path to serve on; derived from the run identity by default").action(async (options) => {
521
+ try {
522
+ exit(await hostWorkflowRun(options, dependencies));
523
+ } catch (error) {
524
+ logError("Unable to host workflow run.", error);
525
+ exit(FAILED_EXIT_CODE);
526
+ }
527
+ });
528
+ }
529
+ const hostRunCommand = createHostRunCommand();
530
+ //#endregion
531
+ //#region src/bin/workflowCommands/flushStdout.ts
532
+ /**
533
+ * Stdout Flush Utility
534
+ *
535
+ * DESIGN PATTERNS:
536
+ * - Small awaitable wrapper around a stream write callback
537
+ *
538
+ * CODING STANDARDS:
539
+ * - Resolve rather than reject so a closed pipe cannot fail a successful command
540
+ *
541
+ * AVOID:
542
+ * - Calling process.exit() straight after writing a large payload to stdout
543
+ */
544
+ const EMPTY_CHUNK = "";
545
+ /**
546
+ * Wait for pending stdout writes to reach the OS before the process exits.
547
+ *
548
+ * Node buffers stdout asynchronously when it is a pipe (but writes synchronously
549
+ * to files and TTYs). `process.exit()` discards whatever is still buffered, so a
550
+ * command that writes a large payload and exits immediately silently truncates
551
+ * its output at the pipe buffer size (64KB on macOS) and emits invalid JSON.
552
+ * Writing an empty chunk and awaiting its flush callback guarantees every earlier
553
+ * write has drained.
554
+ *
555
+ * A write error (for example EPIPE when the reader closed early, as `| head`
556
+ * does) resolves instead of rejecting: the command already produced its output
557
+ * and must not be reported as failed.
558
+ */
559
+ async function flushStdout(stream = process.stdout) {
560
+ await new Promise((resolve) => {
561
+ stream.write(EMPTY_CHUNK, () => resolve());
562
+ });
563
+ }
564
+ //#endregion
565
+ //#region src/bin/workflowCommands/inspectWorkflow.ts
566
+ function parseFormat$1(value) {
567
+ if (value !== "json") throw new commander.InvalidArgumentError("Expected \"json\".");
568
+ return value;
569
+ }
570
+ function isRecord(value) {
571
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
572
+ }
573
+ function createInspectWorkflowCommand(dependencies = {}) {
574
+ const getRuntime = dependencies.getRuntime ?? (() => dependencies.runtime ?? getCliWorkflowRuntime());
575
+ const exit = dependencies.exit ?? ((code) => process.exit(code));
576
+ const writeStdout = dependencies.writeStdout ?? ((message) => process.stdout.write(message));
577
+ const writeStderr = dependencies.writeStderr ?? ((message) => process.stderr.write(message));
578
+ return new commander.Command("inspect-workflow").description("Inspect a workflow definition without executing it").argument("<path>", "Workflow YAML file").requiredOption("--format <format>", "Output format", parseFormat$1).option("--template", "Inspect a partial template without concrete validation").option("--job <id>", "Select a concrete job and its dependencies").action(async (workflowPath, options) => {
579
+ try {
580
+ const runtime = getRuntime();
581
+ const absolutePath = (0, node_path.resolve)(runtime.cwd, workflowPath);
582
+ if (options.template && options.job !== void 0) throw new Error("Template inspection does not support --job.");
583
+ const parser = dependencies.createParser?.(runtime) ?? new require_RecoverWorkflowService.WorkflowParserService(runtime);
584
+ let definition;
585
+ let jobOrder;
586
+ if (options.template === true) {
587
+ definition = await parser.parseWorkflowTemplateFile(absolutePath);
588
+ jobOrder = [];
589
+ } else {
590
+ definition = await parser.parseWorkflowFile(absolutePath);
591
+ jobOrder = parser.resolveJobOrder(definition.jobs, options.job ?? null);
592
+ }
593
+ if (!isRecord(definition)) throw new Error(`Workflow definition is not an object: ${absolutePath}`);
594
+ writeStdout(`${JSON.stringify({
595
+ schemaVersion: 1,
596
+ path: absolutePath,
597
+ template: options.template === true,
598
+ definition,
599
+ jobOrder
600
+ })}\n`);
601
+ await flushStdout();
602
+ exit(0);
603
+ } catch (error) {
604
+ writeStderr(`Error inspecting workflow: ${error instanceof Error ? error.message : String(error)}\n`);
605
+ exit(1);
606
+ }
607
+ });
608
+ }
609
+ const inspectWorkflowCommand = createInspectWorkflowCommand();
610
+ //#endregion
611
+ //#region src/bin/workflowCommands/launchProcess.ts
612
+ const LAUNCHER_CHOICES = [...["tmux", "cmux"], "native"];
613
+ function createLaunchProcessCommand(dependencies = {}) {
614
+ const createService = dependencies.createService ?? (() => new WorkflowLauncherService(getCliWorkflowRuntime(), {
615
+ writeStdout: (text) => process.stdout.write(text),
616
+ writeStderr: (text) => process.stderr.write(text)
617
+ }));
618
+ const exit = dependencies.exit ?? ((code) => process.exit(code));
619
+ const logError = dependencies.logError ?? ((message, error) => console.error(message, error));
620
+ return new commander.Command(LAUNCH_PROCESS_COMMAND_NAME).description("Launch a workflow process in a supported terminal launcher").requiredOption("--name <name>", "Launcher display name").requiredOption("--cwd <path>", "Launcher working directory").requiredOption("--command <command>", "Workflow command to execute").addOption(new commander.Option("--launcher <launcher>", "Terminal launcher").choices([...LAUNCHER_CHOICES])).action(async (options) => {
621
+ try {
622
+ await createService().launch({
623
+ ...options,
624
+ launcher: options.launcher ?? getCliWorkflowRuntime().baseEnvironment.WORKFLOW_LAUNCHER
625
+ });
626
+ } catch (error) {
627
+ logError("Unable to launch workflow process.", error);
628
+ exit(1);
629
+ }
630
+ });
631
+ }
632
+ const launchProcessCommand = createLaunchProcessCommand();
633
+ //#endregion
634
+ //#region src/bin/workflowCommands/listWorkflows.ts
635
+ const DEFAULT_PAGE$1 = 1;
636
+ const DEFAULT_PAGE_SIZE$1 = 20;
637
+ function parsePositiveInteger$1(value) {
638
+ const parsed = Number(value);
639
+ if (!Number.isInteger(parsed) || parsed < 1) throw new commander.InvalidArgumentError("Expected a positive integer.");
640
+ return parsed;
641
+ }
642
+ function parseFormat(value) {
643
+ if (value !== "json" && value !== "text") throw new commander.InvalidArgumentError("Expected \"json\" or \"text\".");
644
+ return value;
645
+ }
646
+ function formatText(result) {
647
+ const header = `Workflows: ${result.total} total | Page: ${result.page} of ${result.totalPages || 0} | Page size: ${result.pageSize}`;
648
+ const tagSummary = result.tags.length > 0 ? `Tags: ${result.tags.map(({ tag, count }) => `${tag} (${count})`).join(", ")}` : "Tags: none";
649
+ const filterSummary = result.tagFilter?.length ? `\nTag filter: ${result.tagFilter.join(", ")}` : "";
650
+ if (result.workflows.length === 0) return `${header}\n${tagSummary}${filterSummary}\n`;
651
+ return `${header}\n${tagSummary}${filterSummary}\n${result.workflows.map(({ path, name, description, tags }) => {
652
+ const label = name || "(unnamed workflow)";
653
+ const entryTags = tags.length > 0 ? `\n Tags: ${tags.join(", ")}` : "";
654
+ return `${path}\n ${label}${description ? `: ${description}` : ""}${entryTags}`;
655
+ }).join("\n")}\n`;
656
+ }
657
+ function createListWorkflowsCommand(dependencies = {}) {
658
+ const exit = dependencies.exit ?? ((code) => process.exit(code));
659
+ const writeStderr = dependencies.writeStderr ?? ((message) => process.stderr.write(message));
660
+ const writeStdout = dependencies.writeStdout ?? ((message) => process.stdout.write(message));
661
+ return new commander.Command("list-workflows").description("List workflow definition files with pagination and filtering").argument("[directory]", "Directory to search", ".").option("--page <number>", "Page number to return", parsePositiveInteger$1, DEFAULT_PAGE$1).option("--page-size <number>", "Number of workflows per page", parsePositiveInteger$1, DEFAULT_PAGE_SIZE$1).option("-f, --filter <text>", "Filter by path, name, description, or tag").option("-t, --tags <tags...>", "Filter by exact tags; all supplied tags must match").option("--format <format>", "Output format: text or json", parseFormat, "text").action(async (directory, options) => {
662
+ try {
663
+ const result = await require_RecoverWorkflowService.listWorkflows(getCliWorkflowRuntime(), directory, options);
664
+ writeStdout(options.format === "json" ? `${JSON.stringify(result, null, 2)}\n` : formatText(result));
665
+ await flushStdout();
666
+ exit(0);
667
+ } catch (error) {
668
+ const message = error instanceof Error ? error.message : String(error);
669
+ writeStderr(`Error listing workflows: ${message}\n`);
670
+ exit(1);
671
+ }
672
+ });
673
+ }
674
+ const listWorkflowsCommand = createListWorkflowsCommand();
675
+ //#endregion
676
+ //#region src/bin/workflowCommands/listWorkflowStatuses.ts
677
+ /**
678
+ * List Workflow Statuses Command
679
+ *
680
+ * DESIGN PATTERNS:
681
+ * - Command pattern with Commander for CLI argument parsing
682
+ * - Service delegation for business logic
683
+ *
684
+ * CODING STANDARDS:
685
+ * - Use async action handlers for asynchronous operations
686
+ * - Handle errors gracefully with process.exit()
687
+ *
688
+ * AVOID:
689
+ * - Hardcoded values (use options or environment variables)
690
+ * - Mixing registry reads with complex formatting logic
691
+ */
692
+ const DEFAULT_ERROR_EXIT_CODE$3 = 1;
693
+ const DEFAULT_PAGE = 1;
694
+ const DEFAULT_PAGE_SIZE = 20;
695
+ const DEFAULT_WORKSPACE_FILTER = "all";
696
+ const PAGE_OPTION_FLAGS = "--page <number>";
697
+ const PAGE_OPTION_DESCRIPTION = "Page number to return";
698
+ const PAGE_SIZE_OPTION_FLAGS = "--page-size <number>";
699
+ const PAGE_SIZE_OPTION_DESCRIPTION = "Number of workflow runs per page";
700
+ const WORKSPACE_OPTION_FLAGS$2 = "-w, --workspace <name>";
701
+ const WORKSPACE_OPTION_DESCRIPTION$2 = "Filter workflow runs by workspace";
702
+ const LIST_WORKFLOW_STATUSES_ERROR_MESSAGE = "Error listing workflow statuses.";
703
+ const LIST_WORKFLOW_STATUSES_ERROR_CODE = "LIST_WORKFLOW_STATUSES_FAILED";
704
+ function parsePositiveInteger(value) {
705
+ const parsed = Number(value);
706
+ if (!Number.isInteger(parsed) || parsed < 1) throw new commander.InvalidArgumentError("Expected a positive integer.");
707
+ return parsed;
708
+ }
709
+ function createListWorkflowStatusesCommand(dependencies = {}) {
710
+ const createRegistry = dependencies.createRegistry ?? (() => new require_RecoverWorkflowService.WorkflowRegistryService(getCliWorkflowRuntime()));
711
+ const exit = dependencies.exit ?? ((code) => process.exit(code));
712
+ const logError = dependencies.logError ?? ((message, error) => console.error(message, error));
713
+ const writeStdout = dependencies.writeStdout ?? ((message) => process.stdout.write(message));
714
+ return new commander.Command(LIST_WORKFLOW_STATUSES_COMMAND_NAME).description(LIST_WORKFLOW_STATUSES_COMMAND_DESCRIPTION).option(PAGE_OPTION_FLAGS, PAGE_OPTION_DESCRIPTION, parsePositiveInteger, DEFAULT_PAGE).option(PAGE_SIZE_OPTION_FLAGS, PAGE_SIZE_OPTION_DESCRIPTION, parsePositiveInteger, DEFAULT_PAGE_SIZE).option(WORKSPACE_OPTION_FLAGS$2, WORKSPACE_OPTION_DESCRIPTION$2, DEFAULT_WORKSPACE_FILTER).option("--reconcile", "Persist stale running workflows as interrupted error records").action(async (options) => {
715
+ try {
716
+ const registry = createRegistry();
717
+ const workspace = options.workspace === DEFAULT_WORKSPACE_FILTER ? void 0 : options.workspace;
718
+ if (options.reconcile) await registry.reconcileStaleRuns(workspace);
719
+ const records = await registry.listRunsPage({
720
+ page: options.page,
721
+ pageSize: options.pageSize,
722
+ workspace
723
+ });
724
+ writeStdout(`${JSON.stringify(records, null, 2)}\n`);
725
+ await flushStdout();
726
+ exit(0);
727
+ } catch (error) {
728
+ const commandError = new WorkflowCommandError(LIST_WORKFLOW_STATUSES_ERROR_MESSAGE, LIST_WORKFLOW_STATUSES_ERROR_CODE, {
729
+ command: LIST_WORKFLOW_STATUSES_COMMAND_NAME,
730
+ workspace: options.workspace ?? DEFAULT_WORKSPACE_FILTER
731
+ }, { cause: error });
732
+ logError(`${commandError.message} [${commandError.code}]`, commandError);
733
+ exit(DEFAULT_ERROR_EXIT_CODE$3);
734
+ }
735
+ });
736
+ }
737
+ const listWorkflowStatusesCommand = createListWorkflowStatusesCommand();
738
+ //#endregion
739
+ //#region src/bin/workflowCommands/recoverWorkflow.ts
740
+ /**
741
+ * RecoverWorkflow Command
742
+ *
743
+ * DESIGN PATTERNS:
744
+ * - Command pattern with Commander for CLI argument parsing
745
+ * - Service delegation for business logic
746
+ *
747
+ * CODING STANDARDS:
748
+ * - Use async action handlers for asynchronous operations
749
+ * - Handle errors gracefully with process.exit()
750
+ *
751
+ * AVOID:
752
+ * - Hardcoded values (use options or environment variables)
753
+ */
754
+ const DEFAULT_ERROR_EXIT_CODE$2 = 1;
755
+ const DEFAULT_WORKSPACE$1 = "default";
756
+ const WORKSPACE_OPTION_FLAGS$1 = "-w, --workspace <name>";
757
+ const WORKSPACE_OPTION_DESCRIPTION$1 = "Workspace containing the failed workflow run";
758
+ const RUNNER_OPTION_FLAGS = "--runner <runner>";
759
+ const RUNNER_OPTION_DESCRIPTION = "Override the runner key for step command maps";
760
+ const DRY_RUN_OPTION_FLAGS = "--dry-run";
761
+ const DRY_RUN_OPTION_DESCRIPTION = "Print recovery steps without executing";
762
+ const RECOVERY_CLAIM_OPTION_FLAGS = "--recovery-claim <claim-id>";
763
+ const RECOVERY_CLAIM_OPTION_DESCRIPTION = "Adopt a registry-issued recovery claim";
764
+ const RECOVER_WORKFLOW_ERROR_MESSAGE = "Error recovering workflow.";
765
+ const RECOVER_WORKFLOW_ERROR_CODE = "RECOVER_WORKFLOW_FAILED";
766
+ /**
767
+ * Recover a failed workflow run from the local workflow registry
768
+ */
769
+ function createRecoverWorkflowCommand(dependencies = {}) {
770
+ const createService = dependencies.createService ?? (() => new require_RecoverWorkflowService.RecoverWorkflowService(getCliWorkflowRuntime()));
771
+ const exit = dependencies.exit ?? ((code) => process.exit(code));
772
+ const logError = dependencies.logError ?? ((message, error) => console.error(message, error));
773
+ return new commander.Command(RECOVER_WORKFLOW_COMMAND_NAME).description(RECOVER_WORKFLOW_COMMAND_DESCRIPTION).argument("<run-key>", "Failed workflow run key").option(WORKSPACE_OPTION_FLAGS$1, WORKSPACE_OPTION_DESCRIPTION$1, DEFAULT_WORKSPACE$1).option(RUNNER_OPTION_FLAGS, RUNNER_OPTION_DESCRIPTION).option(DRY_RUN_OPTION_FLAGS, DRY_RUN_OPTION_DESCRIPTION).option(RECOVERY_CLAIM_OPTION_FLAGS, RECOVERY_CLAIM_OPTION_DESCRIPTION).action(async (runKey, options) => {
774
+ try {
775
+ const result = await createService().recover({
776
+ dryRun: options.dryRun,
777
+ recoveryClaimId: options.recoveryClaim?.trim() || void 0,
778
+ runKey,
779
+ runner: options.runner,
780
+ workspace: options.workspace
781
+ });
782
+ exit(result.exitCode);
783
+ } catch (error) {
784
+ const commandError = new WorkflowCommandError(RECOVER_WORKFLOW_ERROR_MESSAGE, RECOVER_WORKFLOW_ERROR_CODE, {
785
+ command: RECOVER_WORKFLOW_COMMAND_NAME,
786
+ runKey,
787
+ workspace: options.workspace
788
+ }, { cause: error });
789
+ logError(`${commandError.message} [${commandError.code}]`, commandError);
790
+ exit(DEFAULT_ERROR_EXIT_CODE$2);
791
+ }
792
+ });
793
+ }
794
+ const recoverWorkflowCommand = createRecoverWorkflowCommand();
795
+ //#endregion
796
+ //#region src/bin/workflowCommands/runWorkflow.ts
797
+ /**
798
+ * Run Workflow Command
799
+ *
800
+ * DESIGN PATTERNS:
801
+ * - Command pattern with Commander for CLI argument parsing
802
+ * - Service delegation for business logic
803
+ *
804
+ * CODING STANDARDS:
805
+ * - Use async action handlers for asynchronous operations
806
+ * - Handle errors gracefully with process.exit()
807
+ *
808
+ * AVOID:
809
+ * - Hardcoded values (use options or environment variables)
810
+ * - Not exiting with appropriate exit codes on errors
811
+ */
812
+ const DEFAULT_ERROR_EXIT_CODE$1 = 1;
813
+ const KEY_VALUE_DELIMITER = "=";
814
+ const INPUT_OPTION = "--input";
815
+ const ENV_OPTION = "--env";
816
+ const JOB_OPTION = "--job";
817
+ const SECRET_FILE_OPTION = "--secret-file";
818
+ const PROMPT_OPTION = "--prompt";
819
+ const NAME_OPTION = "--name";
820
+ const WORKSPACE_OPTION = "--workspace";
821
+ const DRY_RUN_OPTION = "--dry-run";
822
+ const CONTINUE_ON_ERROR_OPTION = "--continue-on-error";
823
+ const RUNNER_OPTION = "--runner";
824
+ const COMMAND_OPTION = "--command";
825
+ const CHOICE_OPTION = "--choice";
826
+ const PROFILE_OPTION = "--profile";
827
+ const LAUNCHER_OPTION = "--launcher";
828
+ const STATUS_FILE_OPTION = "--status-file";
829
+ const BACKGROUND_OPTION_DESCRIPTION = "Run the workflow in a detached background process";
830
+ const COMMAND_FAILURE_MESSAGE = "Error executing run-workflow.";
831
+ const BACKGROUND_STARTED_MESSAGE = "Started workflow in background";
832
+ const RUN_WORKFLOW_COMMAND_ERROR_CODE = "RUN_WORKFLOW_COMMAND_FAILED";
833
+ const BACKGROUND_CHILD_ENV = "WORKFLOW_MCP_BACKGROUND_CHILD";
834
+ const BACKGROUND_SERVICE_NAME = "workflow-mcp-background-run";
835
+ function parseKeyValueEntries(entries) {
836
+ if (!entries || entries.length === 0) return;
837
+ const values = {};
838
+ for (const entry of entries) {
839
+ const [key, ...rest] = entry.split(KEY_VALUE_DELIMITER);
840
+ values[key] = rest.join(KEY_VALUE_DELIMITER);
841
+ }
842
+ return Object.keys(values).length > 0 ? values : void 0;
843
+ }
844
+ function resolveRunnerOption(options) {
845
+ return options.runner;
846
+ }
847
+ function launchDetachedRun(workflow, options) {
848
+ const { baseEnvironment, cwd, workflowHost } = getCliWorkflowRuntime();
849
+ if (!workflowHost.cliPath) throw new WorkflowCommandError("Unable to determine workflow CLI entry point.", "RUN_WORKFLOW_BACKGROUND_LAUNCH_FAILED", {
850
+ command: RUN_WORKFLOW_COMMAND_NAME,
851
+ workflow
852
+ });
853
+ const args = [
854
+ workflowHost.cliPath,
855
+ RUN_WORKFLOW_COMMAND_NAME,
856
+ workflow
857
+ ];
858
+ if (options.job) args.push(JOB_OPTION, options.job);
859
+ for (const inputEntry of options.input ?? []) args.push(INPUT_OPTION, inputEntry);
860
+ for (const envEntry of options.env ?? []) args.push(ENV_OPTION, envEntry);
861
+ if (options.secretFile) args.push(SECRET_FILE_OPTION, options.secretFile);
862
+ if (options.statusFile) args.push(STATUS_FILE_OPTION, options.statusFile);
863
+ if (options.dryRun) args.push(DRY_RUN_OPTION);
864
+ if (options.continueOnError) args.push(CONTINUE_ON_ERROR_OPTION);
865
+ const runner = resolveRunnerOption(options);
866
+ if (runner) args.push(RUNNER_OPTION, runner);
867
+ if (options.command) args.push(COMMAND_OPTION, options.command);
868
+ if (options.choice) args.push(CHOICE_OPTION, options.choice);
869
+ if (options.profile) args.push(PROFILE_OPTION, options.profile);
870
+ if (options.prompt) args.push(PROMPT_OPTION, options.prompt);
871
+ if (options.launcher) args.push(LAUNCHER_OPTION, options.launcher);
872
+ if (options.name) args.push(NAME_OPTION, options.name);
873
+ if (options.workspace) args.push(WORKSPACE_OPTION, options.workspace);
874
+ const child = workflowHost.spawn(workflowHost.executablePath, args, {
875
+ cwd,
876
+ detached: true,
877
+ env: {
878
+ ...baseEnvironment,
879
+ [BACKGROUND_CHILD_ENV]: "1"
880
+ },
881
+ stdio: "ignore"
882
+ });
883
+ child.unref();
884
+ return child.pid;
885
+ }
886
+ async function registerBackgroundChild(workflow, options) {
887
+ const { baseEnvironment, cwd, workflowHost } = getCliWorkflowRuntime();
888
+ if (baseEnvironment[BACKGROUND_CHILD_ENV] !== "1") return async () => {};
889
+ const registry = workflowHost.processRegistry;
890
+ const repositoryPath = (0, node_path.resolve)(cwd);
891
+ const environment = baseEnvironment.NODE_ENV ?? "development";
892
+ if (!(await registry.registerProcess({
893
+ repositoryPath,
894
+ serviceName: BACKGROUND_SERVICE_NAME,
895
+ serviceType: "tool",
896
+ environment,
897
+ pid: workflowHost.processId,
898
+ command: [
899
+ workflowHost.executablePath,
900
+ workflowHost.cliPath,
901
+ "run-workflow",
902
+ workflow
903
+ ].join(" "),
904
+ args: ["run-workflow", workflow],
905
+ metadata: {
906
+ workflow,
907
+ workspace: options.workspace,
908
+ job: options.job,
909
+ name: options.name,
910
+ runner: options.runner,
911
+ command: options.command,
912
+ choice: options.choice,
913
+ profile: options.profile,
914
+ statusFile: options.statusFile
915
+ },
916
+ force: true
917
+ })).success) return async () => {};
918
+ return async () => {
919
+ const releaseResponse = await registry.releaseProcess({
920
+ repositoryPath,
921
+ serviceName: BACKGROUND_SERVICE_NAME,
922
+ serviceType: "tool",
923
+ environment,
924
+ pid: workflowHost.processId,
925
+ kill: false,
926
+ releasePort: false,
927
+ force: true
928
+ });
929
+ if (!releaseResponse.success && !releaseResponse.error?.includes("No matching process entry")) throw new Error(releaseResponse.error ?? "Failed to release workflow background process");
930
+ };
931
+ }
932
+ function createRunWorkflowCommand(dependencies = {}) {
933
+ const createService = dependencies.createService ?? (() => new require_RecoverWorkflowService.RunWorkflowService(getCliWorkflowLogger(), { runtime: getCliWorkflowRuntime() }));
934
+ const exit = dependencies.exit ?? ((code) => process.exit(code));
935
+ const launchBackgroundRun = dependencies.launchBackgroundRun ?? launchDetachedRun;
936
+ const registerBackgroundChildRelease = dependencies.registerBackgroundChild ?? registerBackgroundChild;
937
+ const logError = dependencies.logError ?? ((message, error) => console.error(message, error));
938
+ const logInfo = dependencies.logInfo ?? ((message) => process.stdout.write(`${message}\n`));
939
+ return new commander.Command(RUN_WORKFLOW_COMMAND_NAME).description(RUN_WORKFLOW_COMMAND_DESCRIPTION).argument("<workflow>", "Path to the workflow YAML file").option("-j, --job <name>", "Run only this job (and its dependencies)").option("-i, --input <key=value...>", "Set workflow_dispatch input (repeatable)").option("-e, --env <key=value...>", "Set extra environment variable (repeatable)").option("--secret-file <path>", "Load secrets from a dotenv-style file").option("--dry-run", "Print steps without executing").option("--continue-on-error", "Continue past step failures").option("--runner <runner>", "Preferred runner key for step command maps").option("--command <name>", "Command templated interactiveRun steps run through (default: each step's first)").option("--choice <name>", "Model choice for steps that do not pin one (default: the choice named \"default\")").option("--profile <name>", "Po profile whose secrets run steps declaring `secrets` receive").addOption(new commander.Option("--launcher <launcher>", "Terminal launcher").choices(["cmux", "tmux"])).option("-p, --prompt <text>", "User prompt for user_prompt trigger workflows").option("-n, --name <name>", "Name for the workflow run context directory").option("-w, --workspace <name>", "Workspace for workflow registry storage").option("--status-file <path>", "Write terminal workflow run JSON to this file after completion").option("--skip-launch", "Skip launch-command delegation (used by inner invocations)").option("-b, --background", BACKGROUND_OPTION_DESCRIPTION).action(async (workflow, options) => {
940
+ try {
941
+ const normalizedOptions = {
942
+ ...options,
943
+ statusFile: options.statusFile ? (0, node_path.resolve)(getCliWorkflowRuntime().cwd, options.statusFile) : void 0
944
+ };
945
+ const service = createService();
946
+ await service.prepareAllocation({
947
+ workflowPath: workflow,
948
+ job: normalizedOptions.job,
949
+ runner: normalizedOptions.runner,
950
+ command: normalizedOptions.command,
951
+ profile: normalizedOptions.profile,
952
+ skipLaunch: normalizedOptions.skipLaunch
953
+ });
954
+ if (normalizedOptions.background) {
955
+ const pid = launchBackgroundRun(workflow, normalizedOptions);
956
+ const pidSuffix = pid ? ` (PID: ${pid})` : "";
957
+ logInfo(`${BACKGROUND_STARTED_MESSAGE}${pidSuffix}`);
958
+ exit(0);
959
+ return;
960
+ }
961
+ const releaseBackgroundChild = await registerBackgroundChildRelease(workflow, normalizedOptions);
962
+ try {
963
+ const runner = resolveRunnerOption(normalizedOptions);
964
+ const result = await service.run({
965
+ runner,
966
+ command: normalizedOptions.command,
967
+ choice: normalizedOptions.choice,
968
+ profile: normalizedOptions.profile,
969
+ workflowPath: workflow,
970
+ job: normalizedOptions.job,
971
+ inputs: parseKeyValueEntries(normalizedOptions.input),
972
+ env: parseKeyValueEntries(normalizedOptions.env),
973
+ secretFile: normalizedOptions.secretFile,
974
+ dryRun: normalizedOptions.dryRun,
975
+ continueOnError: normalizedOptions.continueOnError,
976
+ launcher: normalizedOptions.launcher,
977
+ prompt: normalizedOptions.prompt,
978
+ name: normalizedOptions.name,
979
+ workspace: normalizedOptions.workspace,
980
+ skipLaunch: normalizedOptions.skipLaunch,
981
+ statusFile: normalizedOptions.statusFile
982
+ });
983
+ await releaseBackgroundChild();
984
+ exit(result.exitCode);
985
+ } catch (error) {
986
+ await releaseBackgroundChild();
987
+ throw error;
988
+ }
989
+ } catch (error) {
990
+ const commandError = error instanceof WorkflowCommandError ? error : new WorkflowCommandError(COMMAND_FAILURE_MESSAGE, RUN_WORKFLOW_COMMAND_ERROR_CODE, {
991
+ background: Boolean(options.background),
992
+ command: RUN_WORKFLOW_COMMAND_NAME,
993
+ workflow,
994
+ workspace: options.workspace
995
+ }, { cause: error });
996
+ logError(`${commandError.message} [${commandError.code}]`, commandError);
997
+ exit(DEFAULT_ERROR_EXIT_CODE$1);
998
+ }
999
+ });
1000
+ }
1001
+ const runWorkflowCommand = createRunWorkflowCommand();
1002
+ //#endregion
1003
+ //#region src/bin/workflowCommands/step.ts
1004
+ const DECISION_ERROR_EXIT_CODE = 1;
1005
+ const DECISION_FILE_FLAGS = "--decision-file <path>";
1006
+ const DECISION_FILE_DESCRIPTION = `The step's decision file, named in its instructions (default: $${require_RecoverWorkflowService.WORKFLOW_DECISION_FILE_ENV})`;
1007
+ async function reasonFrom(runtime, options) {
1008
+ const reason = options.reasonFile ? (0, _agimon_ai_po_core_platform.getOrThrow)(await runtime.fs.readTextFile(options.reasonFile, runtime.ioContext)) : options.reason;
1009
+ if (!reason?.trim()) throw new Error("Give a reason with --reason <text> or --reason-file <path>.");
1010
+ return reason.trim();
1011
+ }
1012
+ function createStepCommand(dependencies = {}) {
1013
+ const runtime = dependencies.runtime ?? getCliWorkflowRuntime();
1014
+ const env = dependencies.env ?? runtime.baseEnvironment;
1015
+ const exit = dependencies.exit ?? ((code) => process.exit(code));
1016
+ const writeStderr = dependencies.writeStderr ?? ((message) => process.stderr.write(message));
1017
+ const record = async (options, decision, done) => {
1018
+ try {
1019
+ const path = options.decisionFile ?? env["WORKFLOW_DECISION_FILE"];
1020
+ if (!path) throw new Error(`No decision file: pass ${DECISION_FILE_FLAGS} from the step's instructions, or run inside a workflow step that sets ${require_RecoverWorkflowService.WORKFLOW_DECISION_FILE_ENV}.`);
1021
+ await require_RecoverWorkflowService.recordStepDecision(runtime, path, await decision());
1022
+ writeStderr(`${done}\n`);
1023
+ } catch (error) {
1024
+ writeStderr(`${error instanceof Error ? error.message : String(error)}\n`);
1025
+ exit(DECISION_ERROR_EXIT_CODE);
1026
+ }
1027
+ };
1028
+ const command = new commander.Command(STEP_COMMAND_NAME).description(STEP_COMMAND_DESCRIPTION);
1029
+ command.command("complete").description("The step finished its work").option("-s, --summary <text>", "One line on what the step did").option(DECISION_FILE_FLAGS, DECISION_FILE_DESCRIPTION).action(async (options) => {
1030
+ await record(options, async () => ({
1031
+ decision: "complete",
1032
+ ...options.summary?.trim() ? { summary: options.summary.trim() } : {}
1033
+ }), "Recorded: step complete. You can stop now.");
1034
+ });
1035
+ command.command("fix").description("An earlier job must fix something before this step can pass").requiredOption("--restart-from <job>", "Job the workflow restarts from to fix it").option("--reason <text>", "What must be fixed, and where").option("--reason-file <path>", "Read the reason from a file").option(DECISION_FILE_FLAGS, DECISION_FILE_DESCRIPTION).action(async (options) => {
1036
+ await record(options, async () => ({
1037
+ decision: "fix",
1038
+ restartFrom: options.restartFrom,
1039
+ reason: await reasonFrom(runtime, options)
1040
+ }), `Recorded: fix from "${options.restartFrom}". You can stop now.`);
1041
+ });
1042
+ command.command("fail").description("A blocker this workflow cannot fix; ends the run").option("--reason <text>", "The blocker and its evidence").option("--reason-file <path>", "Read the reason from a file").option(DECISION_FILE_FLAGS, DECISION_FILE_DESCRIPTION).action(async (options) => {
1043
+ await record(options, async () => ({
1044
+ decision: "fail",
1045
+ reason: await reasonFrom(runtime, options)
1046
+ }), "Recorded: step failed. You can stop now.");
1047
+ });
1048
+ return command;
1049
+ }
1050
+ const stepCommand = createStepCommand();
1051
+ //#endregion
1052
+ //#region src/bin/workflowCommands/stopWorkflow.ts
1053
+ /**
1054
+ * Stop Workflow Command
1055
+ *
1056
+ * DESIGN PATTERNS:
1057
+ * - Command pattern with Commander for CLI argument parsing
1058
+ * - Service delegation for business logic
1059
+ *
1060
+ * CODING STANDARDS:
1061
+ * - Use async action handlers for asynchronous operations
1062
+ * - Handle errors gracefully with process.exit()
1063
+ *
1064
+ * AVOID:
1065
+ * - Hardcoded values (use options or environment variables)
1066
+ * - Touching terminal stdin/raw mode for workflow cancellation
1067
+ */
1068
+ const DEFAULT_ERROR_EXIT_CODE = 1;
1069
+ const DEFAULT_WORKSPACE = "default";
1070
+ const WORKSPACE_OPTION_FLAGS = "-w, --workspace <name>";
1071
+ const WORKSPACE_OPTION_DESCRIPTION = "Workspace containing the running workflow";
1072
+ const RUN_ID_OPTION_FLAGS = "--run-id <run-id>";
1073
+ const RUN_ID_OPTION_DESCRIPTION = "Exact running generation to stop";
1074
+ const REASON_OPTION_FLAGS = "-r, --reason <text>";
1075
+ const REASON_OPTION_DESCRIPTION = "Optional stop reason to record";
1076
+ const STOP_WORKFLOW_ERROR_MESSAGE = "Error requesting workflow stop.";
1077
+ const STOP_WORKFLOW_ERROR_CODE = "STOP_WORKFLOW_FAILED";
1078
+ function createStopWorkflowCommand(dependencies = {}) {
1079
+ const createRegistry = dependencies.createRegistry ?? (() => new require_RecoverWorkflowService.WorkflowRegistryService(getCliWorkflowRuntime()));
1080
+ const exit = dependencies.exit ?? ((code) => process.exit(code));
1081
+ const logError = dependencies.logError ?? ((message, error) => console.error(message, error));
1082
+ const writeStdout = dependencies.writeStdout ?? ((message) => process.stdout.write(message));
1083
+ return new commander.Command(STOP_WORKFLOW_COMMAND_NAME).description(STOP_WORKFLOW_COMMAND_DESCRIPTION).argument("<run-key>", "Running workflow run key").option(WORKSPACE_OPTION_FLAGS, WORKSPACE_OPTION_DESCRIPTION, DEFAULT_WORKSPACE).requiredOption(RUN_ID_OPTION_FLAGS, RUN_ID_OPTION_DESCRIPTION).option(REASON_OPTION_FLAGS, REASON_OPTION_DESCRIPTION).action(async (runKey, options) => {
1084
+ try {
1085
+ const registry = createRegistry();
1086
+ const request = await registry.requestStop(options.workspace, runKey, options.reason, options.runId);
1087
+ writeStdout(`${JSON.stringify({
1088
+ reason: request.reason,
1089
+ requestedAt: request.requestedAt,
1090
+ runKey,
1091
+ workspace: registry.resolveWorkspace(options.workspace)
1092
+ }, null, 2)}\n`);
1093
+ exit(0);
1094
+ } catch (error) {
1095
+ const commandError = new WorkflowCommandError(STOP_WORKFLOW_ERROR_MESSAGE, STOP_WORKFLOW_ERROR_CODE, {
1096
+ command: STOP_WORKFLOW_COMMAND_NAME,
1097
+ runKey,
1098
+ workspace: options.workspace
1099
+ }, { cause: error });
1100
+ logError(`${commandError.message} [${commandError.code}]`, commandError);
1101
+ exit(DEFAULT_ERROR_EXIT_CODE);
1102
+ }
1103
+ });
1104
+ }
1105
+ const stopWorkflowCommand = createStopWorkflowCommand();
1106
+ //#endregion
1107
+ //#region src/bin/workflowMcp.ts
1108
+ /**
1109
+ * MCP Server Entry Point
1110
+ *
1111
+ * DESIGN PATTERNS:
1112
+ * - CLI pattern with Commander for argument parsing
1113
+ * - Command pattern for organizing CLI commands
1114
+ * - Transport abstraction for multiple communication methods
1115
+ *
1116
+ * CODING STANDARDS:
1117
+ * - Use async/await for asynchronous operations
1118
+ * - Handle errors gracefully with try-catch
1119
+ * - Register all commands in main entry point
1120
+ *
1121
+ * AVOID:
1122
+ * - Hardcoding command logic in index.ts (use separate command files)
1123
+ * - Missing error handling for command execution
1124
+ */
1125
+ const CLI_NAME = "workflow-mcp";
1126
+ installOtelErrorLogger({ serviceName: CLI_NAME });
1127
+ async function main() {
1128
+ const program = new commander.Command();
1129
+ program.name(CLI_NAME).description("Run, inspect and control local workflows").version(require_RecoverWorkflowService.readWorkflowPackageVersion());
1130
+ program.addCommand(listWorkflowsCommand);
1131
+ program.addCommand(listWorkflowStatusesCommand);
1132
+ program.addCommand(launchProcessCommand);
1133
+ program.addCommand(hostRunCommand);
1134
+ program.addCommand(inspectWorkflowCommand);
1135
+ program.addCommand(closeLauncherCommand);
1136
+ program.addCommand(describeRunCommand);
1137
+ program.addCommand(doctorCommand);
1138
+ program.addCommand(pauseWorkflowCommand);
1139
+ program.addCommand(resumeWorkflowCommand);
1140
+ program.addCommand(recoverWorkflowCommand);
1141
+ program.addCommand(runWorkflowCommand);
1142
+ program.addCommand(stepCommand);
1143
+ program.addCommand(stopWorkflowCommand);
1144
+ program.command("require-capability <name>").description("Fail unless this runtime implements a required feature (not acceptance proof)").action(require_RecoverWorkflowService.requireWorkflowCapability);
1145
+ await program.parseAsync(process.argv);
1146
+ }
1147
+ main().catch((error) => {
1148
+ getCliWorkflowLogger().error(`[CLI_STARTUP_ERROR] ${CLI_NAME} startup failed: ${error instanceof Error ? error.message : String(error)}`);
1149
+ process.exit(1);
1150
+ });
1151
+ //#endregion
1152
+
1153
+ //# sourceMappingURL=cli.cjs.map