@lukstei/dsh-yaml-workflow 0.0.0-stage → 0.2.2-rc.5.4

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.
package/src/runner.ts ADDED
@@ -0,0 +1,1955 @@
1
+ /**
2
+ * PURPOSE: Stateless workflow execution loop and orchestrator.
3
+ * ALLOWED: Interpreting pure transitions, coordinating steps via WorkflowEffectContext, abort handling.
4
+ * FORBIDDEN: Direct command registration, direct filesystem access, Cordis runtime coupling.
5
+ */
6
+
7
+ import crypto from "node:crypto";
8
+ import path from "node:path";
9
+ import type { CommandResult } from "@deepseek-ai/dsh-commands";
10
+ import type { WorkflowEffectContext } from "./effects.ts";
11
+ import {
12
+ formatOutputRetryPrompt,
13
+ formatValidationSummary,
14
+ formatWorkflowList,
15
+ interpolateSubagentConfig,
16
+ interpolateTemplate,
17
+ normalizeSubagentConfig,
18
+ type OutputRetryMissingItem,
19
+ parseInvocationInput,
20
+ parseListOutput,
21
+ parseSubagentShorthand,
22
+ parseWorkflowDocument,
23
+ parseWorkflowSummary,
24
+ resolveGate,
25
+ resolveWorkflowArgs,
26
+ } from "./parser.ts";
27
+ import { nextWorkflowRequest } from "./requests.ts";
28
+ import { formatValidationErrors, validateWorkflow } from "./rules.ts";
29
+ import {
30
+ applyAbort,
31
+ applyGatePause,
32
+ applyStepPause,
33
+ computeStepTransition,
34
+ foldWorkflowState,
35
+ } from "./transitions.ts";
36
+ import type {
37
+ SubagentConfig,
38
+ SubagentDispatchResult,
39
+ WorkflowDocument,
40
+ WorkflowEffect,
41
+ WorkflowInvocation,
42
+ WorkflowRun,
43
+ WorkflowState,
44
+ WorkflowStep,
45
+ WorkflowStepOutputsMap,
46
+ WorkflowSummary,
47
+ } from "./types.ts";
48
+
49
+ /**
50
+ * Narrowed error result for command validation failures.
51
+ */
52
+ type CommandErrorResult = Extract<CommandResult, { kind: "error" }>;
53
+
54
+ /**
55
+ * Validated workflow ready for execution.
56
+ */
57
+ export interface ValidatedWorkflow {
58
+ readonly kind: "valid";
59
+ readonly doc: WorkflowDocument;
60
+ readonly invocation: WorkflowInvocation;
61
+ readonly state: WorkflowState;
62
+ }
63
+
64
+ const executingSessions = new Set<string>();
65
+
66
+ /**
67
+ * Purpose: Validates and durably accepts a workflow command without retaining its YAML.
68
+ * Contract:
69
+ * - Inputs: command input, effects, and the originating /wf command ID.
70
+ * - Outputs: immediate validation diagnostics or a queued acknowledgement.
71
+ * - Throws / Errors: unexpected event-write failures propagate.
72
+ */
73
+ export async function requestWorkflow(
74
+ rawInput: string,
75
+ effects: WorkflowEffectContext,
76
+ runId: string,
77
+ ): Promise<CommandResult> {
78
+ const validated = await validateWorkflowInvocation(rawInput, effects, runId);
79
+ if (validated.kind === "error") return validated;
80
+ effects.emit({ action: "request", rawInput, runId });
81
+ return { kind: "success", text: "Workflow queued" };
82
+ }
83
+
84
+ /**
85
+ * Purpose: Drains accepted requests after the preceding workflow finishes cleanup.
86
+ * Contract:
87
+ * - Inputs: effects for a live session whose command lifecycle is recorded.
88
+ * - Outputs: requests execute FIFO; running or paused workflows keep requests pending.
89
+ * - Throws / Errors: unexpected event-write failures propagate; validation failures are recorded.
90
+ */
91
+ export async function drainWorkflowRequests(
92
+ effects: WorkflowEffectContext,
93
+ ): Promise<void> {
94
+ if (executingSessions.has(effects.sessionId)) return;
95
+ executingSessions.add(effects.sessionId);
96
+ try {
97
+ while (true) {
98
+ const events = effects.snapshotEvents();
99
+ const active = foldWorkflowState(events);
100
+ if (
101
+ active !== null &&
102
+ (active.state.status === "running" || active.state.status === "paused")
103
+ )
104
+ return;
105
+ const request = nextWorkflowRequest(events);
106
+ if (request === undefined) return;
107
+ const startupAbortController = new AbortController();
108
+ const cleanupStartupAbort = effects.watchAbort(startupAbortController);
109
+ let validated: ValidatedWorkflow | CommandErrorResult;
110
+ try {
111
+ await effects.whenIdle();
112
+ validated = await validateWorkflowInvocation(
113
+ request.rawInput,
114
+ effects,
115
+ request.runId,
116
+ );
117
+ } catch (error: unknown) {
118
+ validated = { kind: "error", text: extractErrorMessage(error) };
119
+ } finally {
120
+ cleanupStartupAbort();
121
+ }
122
+ if (validated.kind === "error") {
123
+ effects.emit({ action: "request-failed", runId: request.runId });
124
+ effects.emit({
125
+ action: "step",
126
+ id: `wf-request-${request.runId}-failed`,
127
+ stepIndex: 0,
128
+ label: `Queued workflow failed: ${validated.text}`,
129
+ kind: "error",
130
+ runId: request.runId,
131
+ });
132
+ } else {
133
+ await executeValidatedWorkflowDirect(
134
+ validated,
135
+ effects,
136
+ startupAbortController.signal,
137
+ );
138
+ }
139
+ }
140
+ } finally {
141
+ executingSessions.delete(effects.sessionId);
142
+ }
143
+ }
144
+
145
+ /**
146
+ * Purpose: Wakes pending workflows and reports unexpected background failures.
147
+ * Contract:
148
+ * - Inputs: effects for the session whose admission or execution just settled.
149
+ * - Outputs: starts at most one drain; failures are logged.
150
+ * - Throws / Errors: asynchronous errors are reported through logInfo.
151
+ */
152
+ export function startPendingWorkflows(effects: WorkflowEffectContext): void {
153
+ void drainWorkflowRequests(effects).catch((error: unknown) => {
154
+ effects.logInfo(`Workflow queue failed: ${extractErrorMessage(error)}`);
155
+ });
156
+ }
157
+
158
+ async function withWorkflowExecution(
159
+ effects: WorkflowEffectContext,
160
+ execute: () => Promise<CommandResult>,
161
+ ): Promise<CommandResult> {
162
+ if (executingSessions.has(effects.sessionId)) {
163
+ return {
164
+ kind: "error",
165
+ text: "A workflow is already executing in this session",
166
+ };
167
+ }
168
+ executingSessions.add(effects.sessionId);
169
+ try {
170
+ return await execute();
171
+ } finally {
172
+ executingSessions.delete(effects.sessionId);
173
+ startPendingWorkflows(effects);
174
+ }
175
+ }
176
+
177
+ /**
178
+ * Handles workflow abortion by computing aborted transition and emitting state.
179
+ */
180
+ function handleAbort(
181
+ effects: WorkflowEffectContext,
182
+ state: WorkflowState,
183
+ stepIndex: number,
184
+ totalSteps: number,
185
+ runId: string,
186
+ ): CommandResult {
187
+ effects.emit({
188
+ action: "state",
189
+ ...applyAbort(state, totalSteps, false).nextState,
190
+ runId,
191
+ });
192
+ return {
193
+ kind: "error",
194
+ text: `Workflow aborted at step ${stepIndex + 1}/${totalSteps}`,
195
+ };
196
+ }
197
+
198
+ /**
199
+ * Checks whether an abort signal was triggered specifically to pause the workflow.
200
+ */
201
+ function isPauseSignal(signal: AbortSignal): boolean {
202
+ const reason = signal.reason as { kind?: string } | undefined;
203
+ return reason?.kind === "pause";
204
+ }
205
+
206
+ /**
207
+ * Handles workflow pause (e.g. user interrupted via Stop Generating) by computing paused transition and emitting state.
208
+ */
209
+ function handlePause(
210
+ effects: WorkflowEffectContext,
211
+ state: WorkflowState,
212
+ stepIndex: number,
213
+ stepLabel: string,
214
+ totalSteps: number,
215
+ runId: string,
216
+ ): CommandResult {
217
+ const pauseTransition = applyStepPause(state, stepLabel);
218
+ effects.emit({
219
+ action: "state",
220
+ ...pauseTransition.nextState,
221
+ runId,
222
+ });
223
+ return {
224
+ kind: "success",
225
+ text: `Workflow paused at step ${stepIndex + 1}/${totalSteps}. Resume with /wf-resume`,
226
+ };
227
+ }
228
+
229
+ /**
230
+ * Handles workflow termination (either pause on user stop or hard abort) by computing transition and emitting state.
231
+ */
232
+ function handleTermination(
233
+ signal: AbortSignal,
234
+ effects: WorkflowEffectContext,
235
+ state: WorkflowState,
236
+ stepIndex: number,
237
+ stepLabel: string,
238
+ totalSteps: number,
239
+ runId: string,
240
+ ): CommandResult {
241
+ if (isPauseSignal(signal)) {
242
+ return handlePause(effects, state, stepIndex, stepLabel, totalSteps, runId);
243
+ }
244
+ return handleAbort(effects, state, stepIndex, totalSteps, runId);
245
+ }
246
+
247
+ /**
248
+ * Emits completion state and returns success result.
249
+ */
250
+ function completeWorkflow(
251
+ effects: WorkflowEffectContext,
252
+ totalSteps: number,
253
+ outputs: Record<string, string | readonly string[]> | undefined,
254
+ runId: string,
255
+ ): CommandResult {
256
+ const hasOutputs = outputs !== undefined && Object.keys(outputs).length > 0;
257
+ effects.emit({
258
+ action: "state",
259
+ stepIndex: totalSteps,
260
+ status: "completed",
261
+ ...(hasOutputs ? { outputs } : {}),
262
+ runId,
263
+ });
264
+ return {
265
+ kind: "success",
266
+ text: `Completed workflow (${totalSteps} steps)`,
267
+ };
268
+ }
269
+
270
+ /**
271
+ * Safely extracts error message string from unknown error.
272
+ */
273
+ function extractErrorMessage(err: unknown): string {
274
+ return (err instanceof Error ? err.message : String(err)) || "Unknown error";
275
+ }
276
+
277
+ /**
278
+ * Emits aborted state, logs error, and returns CommandErrorResult on unhandled execution failure.
279
+ */
280
+ function handleExecutionFailure(
281
+ effects: WorkflowEffectContext,
282
+ state: WorkflowState,
283
+ action: "execution" | "resume",
284
+ err: unknown,
285
+ totalSteps: number,
286
+ runId: string,
287
+ ): CommandErrorResult {
288
+ const message = extractErrorMessage(err);
289
+ const failedStepIndex = Math.min(state.stepIndex, totalSteps - 1);
290
+ const displayStep = failedStepIndex + 1;
291
+ const { pauseReason: _pauseReason, ...cleanState } = state;
292
+ effects.emit({
293
+ action: "state",
294
+ ...cleanState,
295
+ stepIndex: failedStepIndex,
296
+ status: "aborted",
297
+ error: message,
298
+ runId,
299
+ });
300
+ effects.logInfo(
301
+ `Workflow ${action} failed at step ${displayStep}/${totalSteps}: ${message}`,
302
+ );
303
+ return {
304
+ kind: "error",
305
+ text: `Workflow ${action} failed at step ${displayStep}/${totalSteps}: ${message}`,
306
+ };
307
+ }
308
+
309
+ /**
310
+ * Type predicate ensuring an unknown value is a non-null, non-array object.
311
+ */
312
+ function isRecord(value: unknown): value is Record<string, unknown> {
313
+ return typeof value === "object" && value !== null && !Array.isArray(value);
314
+ }
315
+
316
+ /**
317
+ * Detects whether an error indicates Cordis context inactivation during fiber unload.
318
+ */
319
+ function isInactiveContextError(err: unknown): boolean {
320
+ if (isRecord(err) && err.code === "INACTIVE_EFFECT") {
321
+ return true;
322
+ }
323
+ // edge case: Cordis throws a generic Error containing "inactive context" when session or fiber unloads mid-turn
324
+ return extractErrorMessage(err).includes("inactive context");
325
+ }
326
+
327
+ /**
328
+ * Detects whether an error represents a tool, subagent, or user-initiated cancellation.
329
+ */
330
+ function isAbortError(err: unknown): boolean {
331
+ if (!err) return false;
332
+ if (err instanceof Error && err.name === "AbortError") return true;
333
+ if (isRecord(err)) {
334
+ const code = err.code;
335
+ return (
336
+ code === "ABORTED" ||
337
+ code === "TOOL_ABORTED" ||
338
+ code === "TOOL_ABORTED_BEFORE_DISPATCH"
339
+ );
340
+ }
341
+ return false;
342
+ }
343
+
344
+ /**
345
+ * Resolves declared file output paths against template arguments and workflow effect context.
346
+ */
347
+ function resolveStepOutputFilePaths(
348
+ outputsDef: WorkflowStepOutputsMap | undefined,
349
+ args: Record<string, string>,
350
+ currentOutputs: Readonly<Record<string, string | readonly string[]>>,
351
+ effects: WorkflowEffectContext,
352
+ ): Record<string, string> {
353
+ const resolved: Record<string, string> = {};
354
+ if (!outputsDef) return resolved;
355
+ for (const [name, def] of Object.entries(outputsDef)) {
356
+ if (def.type === "file") {
357
+ const interpolatedPath = interpolateTemplate(
358
+ def.path,
359
+ args,
360
+ currentOutputs,
361
+ );
362
+ resolved[name] = effects.resolveOutputPath(interpolatedPath, def.base);
363
+ }
364
+ }
365
+ return resolved;
366
+ }
367
+
368
+ /**
369
+ * Unifies error classification, pause handling, abort handling, and failure delegation during workflow execution.
370
+ */
371
+ function handleWorkflowExecutionError({
372
+ effects,
373
+ state,
374
+ doc,
375
+ signal,
376
+ err,
377
+ action,
378
+ runId,
379
+ }: {
380
+ effects: WorkflowEffectContext;
381
+ state: WorkflowState;
382
+ doc: WorkflowDocument;
383
+ signal: AbortSignal;
384
+ err: unknown;
385
+ action: "execution" | "resume";
386
+ runId: string;
387
+ }): CommandResult {
388
+ const currentIdx = Math.min(state.stepIndex, doc.steps.length - 1);
389
+ const stepName = doc.steps[currentIdx].name;
390
+ if (signal.aborted || isAbortError(err)) {
391
+ return handleTermination(
392
+ signal,
393
+ effects,
394
+ state,
395
+ currentIdx,
396
+ stepName,
397
+ doc.steps.length,
398
+ runId,
399
+ );
400
+ }
401
+ if (isInactiveContextError(err)) {
402
+ return handlePause(
403
+ effects,
404
+ state,
405
+ currentIdx,
406
+ stepName,
407
+ doc.steps.length,
408
+ runId,
409
+ );
410
+ }
411
+ return handleExecutionFailure(
412
+ effects,
413
+ state,
414
+ action,
415
+ err,
416
+ doc.steps.length,
417
+ runId,
418
+ );
419
+ }
420
+
421
+ /**
422
+ * Validates session ID and awaits agent idle state before workflow resumption or discarding.
423
+ */
424
+ async function ensureIdleSession(
425
+ effects: WorkflowEffectContext,
426
+ action: "resume" | "discard",
427
+ ): Promise<CommandErrorResult | undefined> {
428
+ if (!effects.sessionId) {
429
+ return {
430
+ kind: "error",
431
+ text: `Workflow ${action} failed: agent session ID is required`,
432
+ };
433
+ }
434
+ try {
435
+ await effects.whenIdle();
436
+ } catch (err: unknown) {
437
+ const message = extractErrorMessage(err);
438
+ effects.logInfo(`Workflow ${action} failed: ${message}`);
439
+ return {
440
+ kind: "error",
441
+ text: `Workflow ${action} failed: ${message}`,
442
+ };
443
+ }
444
+ return undefined;
445
+ }
446
+
447
+ /**
448
+ * Runs a validation step and catches errors into a formatted CommandErrorResult.
449
+ */
450
+ function runValidationStep<T>(
451
+ fn: () => T,
452
+ prefix: string,
453
+ targetPath: string,
454
+ ): { readonly result: T } | CommandErrorResult {
455
+ try {
456
+ return { result: fn() };
457
+ } catch (err: unknown) {
458
+ return {
459
+ kind: "error",
460
+ text: `${prefix} '${targetPath}': ${extractErrorMessage(err)}`,
461
+ };
462
+ }
463
+ }
464
+
465
+ /**
466
+ * Drives sequential workflow step execution, interpreting pure state machine transitions.
467
+ * CONTRACT:
468
+ * - Input: effects, doc, invocation, initial state, optional signal, and instructions.
469
+ * - Output: Promise resolving to CommandResult (success, gate pause, or abort error).
470
+ */
471
+ async function runWorkflowSteps({
472
+ effects,
473
+ doc,
474
+ invocation,
475
+ stateRef,
476
+ signal,
477
+ instructions,
478
+ }: {
479
+ effects: WorkflowEffectContext;
480
+ doc: WorkflowDocument;
481
+ invocation: WorkflowInvocation;
482
+ stateRef: { current: WorkflowState };
483
+ signal: AbortSignal;
484
+ instructions?: string;
485
+ }): Promise<CommandResult> {
486
+ const steps = doc.steps;
487
+ const runId = invocation.runId;
488
+ const initialState = stateRef.current;
489
+ let state: WorkflowState = initialState;
490
+ const outputs: Record<string, string | readonly string[]> = {
491
+ ...initialState.outputs,
492
+ };
493
+ let pendingInstructions: string | undefined = instructions;
494
+
495
+ const hasScratchOutput = steps.some(
496
+ (s) =>
497
+ (s.kind === "prompt" || s.kind === "subagent") &&
498
+ s.outputs !== undefined &&
499
+ Object.values(s.outputs).some(
500
+ (o) => o.type === "file" && o.base === "scratch",
501
+ ),
502
+ );
503
+ if (hasScratchOutput) {
504
+ await effects.ensureScratchDirectory();
505
+ }
506
+
507
+ while (state.stepIndex < steps.length) {
508
+ const currentStepIndex = state.stepIndex;
509
+ if (signal.aborted) {
510
+ return handleTermination(
511
+ signal,
512
+ effects,
513
+ stateRef.current,
514
+ currentStepIndex,
515
+ steps[currentStepIndex].name,
516
+ steps.length,
517
+ runId,
518
+ );
519
+ }
520
+ const step = steps[currentStepIndex];
521
+
522
+ if (step.kind === "subagent") {
523
+ let waveEnd = currentStepIndex;
524
+ while (waveEnd < steps.length) {
525
+ const s = steps[waveEnd];
526
+ if (s.kind !== "subagent") break;
527
+ const sGate = resolveGate(
528
+ s.gate,
529
+ invocation.resolvedArgs,
530
+ outputs,
531
+ s.name,
532
+ );
533
+ if (sGate !== undefined) {
534
+ waveEnd++;
535
+ break;
536
+ }
537
+ waveEnd++;
538
+ }
539
+
540
+ interface ActiveWaveStep {
541
+ readonly stepIndex: number;
542
+ readonly itemIndex?: number;
543
+ readonly totalItems?: number;
544
+ readonly step: Extract<WorkflowStep, { kind: "subagent" }>;
545
+ readonly effect: Extract<WorkflowEffect, { type: "subagent" }>;
546
+ readonly resolvedOutputPaths: Record<string, string>;
547
+ }
548
+
549
+ const activeWaveSteps: ActiveWaveStep[] = [];
550
+ for (let idx = currentStepIndex; idx < waveEnd; idx++) {
551
+ // type-safe: waveEnd bounds guarantee steps[idx].kind === "subagent"
552
+ const waveStep = steps[idx] as Extract<
553
+ WorkflowStep,
554
+ { kind: "subagent" }
555
+ >;
556
+
557
+ if (waveStep.foreach !== undefined) {
558
+ const stepOutputPaths = resolveStepOutputFilePaths(
559
+ waveStep.outputs,
560
+ invocation.resolvedArgs,
561
+ outputs,
562
+ effects,
563
+ );
564
+ const transition = computeStepTransition({
565
+ doc,
566
+ invocation,
567
+ state: { ...state, stepIndex: idx },
568
+ instructions: pendingInstructions,
569
+ outputs,
570
+ resolvedOutputPaths: stepOutputPaths,
571
+ });
572
+
573
+ if (transition.effect.type === "skip") {
574
+ continue;
575
+ }
576
+
577
+ const listName = waveStep.foreach.slice(10, -2);
578
+ const rawVal = outputs[listName];
579
+ if (!Array.isArray(rawVal)) {
580
+ return handleExecutionFailure(
581
+ effects,
582
+ stateRef.current,
583
+ "execution",
584
+ new Error(
585
+ `Step ${idx + 1} foreach output '${listName}' is missing or not an array`,
586
+ ),
587
+ steps.length,
588
+ runId,
589
+ );
590
+ }
591
+ const listItems: readonly string[] = rawVal;
592
+
593
+ if (listItems.length === 0) {
594
+ if (waveStep.output !== undefined) {
595
+ effects.recordOutput(
596
+ idx,
597
+ waveStep.output,
598
+ "[]",
599
+ "list",
600
+ undefined,
601
+ runId,
602
+ );
603
+ outputs[waveStep.output] = [];
604
+ }
605
+ if (waveStep.outputs !== undefined) {
606
+ for (const name of Object.keys(waveStep.outputs)) {
607
+ effects.recordOutput(idx, name, "[]", "list", undefined, runId);
608
+ outputs[name] = [];
609
+ }
610
+ }
611
+ continue;
612
+ }
613
+
614
+ // type-safe: transition.effect is guaranteed to be subagent effect when transition.effect.type !== "skip"
615
+ const baseSubagentEffect = transition.effect as Extract<
616
+ WorkflowEffect,
617
+ { type: "subagent" }
618
+ >;
619
+
620
+ for (let itemIdx = 0; itemIdx < listItems.length; itemIdx++) {
621
+ const itemVal = listItems[itemIdx];
622
+ const itemPromptText = interpolateTemplate(
623
+ baseSubagentEffect.promptText,
624
+ invocation.resolvedArgs,
625
+ outputs,
626
+ { item: itemVal },
627
+ );
628
+
629
+ const itemLabel = `Step ${idx + 1} (${itemIdx + 1}/${listItems.length}): ${waveStep.name} [${itemVal}]`;
630
+
631
+ const subagentEffect: Extract<
632
+ WorkflowEffect,
633
+ { type: "subagent" }
634
+ > = {
635
+ ...baseSubagentEffect,
636
+ promptText: itemPromptText,
637
+ stepLabel: itemLabel,
638
+ };
639
+
640
+ activeWaveSteps.push({
641
+ stepIndex: idx,
642
+ itemIndex: itemIdx,
643
+ totalItems: listItems.length,
644
+ step: waveStep,
645
+ effect: subagentEffect,
646
+ resolvedOutputPaths: stepOutputPaths,
647
+ });
648
+ }
649
+ } else {
650
+ const stepOutputPaths = resolveStepOutputFilePaths(
651
+ waveStep.outputs,
652
+ invocation.resolvedArgs,
653
+ outputs,
654
+ effects,
655
+ );
656
+
657
+ const transition = computeStepTransition({
658
+ doc,
659
+ invocation,
660
+ state: { ...state, stepIndex: idx },
661
+ instructions: pendingInstructions,
662
+ outputs,
663
+ resolvedOutputPaths: stepOutputPaths,
664
+ });
665
+
666
+ if (transition.effect.type === "skip") {
667
+ continue;
668
+ }
669
+
670
+ // type-safe: computeStepTransition produces subagent effect for non-skipped subagent steps
671
+ const subagentEffect = transition.effect as Extract<
672
+ WorkflowEffect,
673
+ { type: "subagent" }
674
+ >;
675
+
676
+ activeWaveSteps.push({
677
+ stepIndex: idx,
678
+ step: waveStep,
679
+ effect: subagentEffect,
680
+ resolvedOutputPaths: stepOutputPaths,
681
+ });
682
+ }
683
+ }
684
+
685
+ if (activeWaveSteps.length === 0) {
686
+ state = {
687
+ ...state,
688
+ stepIndex: waveEnd,
689
+ ...(Object.keys(outputs).length > 0
690
+ ? { outputs: { ...outputs } }
691
+ : {}),
692
+ };
693
+ stateRef.current = state;
694
+ if (state.stepIndex < steps.length) {
695
+ effects.emit({
696
+ action: "state",
697
+ ...state,
698
+ runId,
699
+ });
700
+ }
701
+ continue;
702
+ }
703
+
704
+ for (const item of activeWaveSteps) {
705
+ const stepId =
706
+ item.itemIndex !== undefined
707
+ ? `wf-step-${runId}-${item.stepIndex}-${item.itemIndex}`
708
+ : `wf-step-${runId}-${item.stepIndex}`;
709
+ effects.emit({
710
+ action: "step",
711
+ id: stepId,
712
+ stepIndex: item.stepIndex,
713
+ label: item.effect.stepLabel,
714
+ kind: "success",
715
+ runId,
716
+ });
717
+ }
718
+
719
+ const waveAbortController = new AbortController();
720
+ const waveSignal = AbortSignal.any([signal, waveAbortController.signal]);
721
+
722
+ let waveResults: Array<
723
+ ActiveWaveStep & { readonly subagentResult: SubagentDispatchResult }
724
+ >;
725
+
726
+ let failingStepIndex = activeWaveSteps[0].stepIndex;
727
+ try {
728
+ waveResults = await Promise.all(
729
+ activeWaveSteps.map(async (item) => {
730
+ try {
731
+ const subagentResult = await effects.dispatchSubagent(
732
+ item.effect,
733
+ waveSignal,
734
+ );
735
+ return { ...item, subagentResult };
736
+ } catch (err: unknown) {
737
+ if (!waveAbortController.signal.aborted) {
738
+ failingStepIndex = item.stepIndex;
739
+ }
740
+ waveAbortController.abort({ kind: "error" });
741
+ throw err;
742
+ }
743
+ }),
744
+ );
745
+ } catch (err: unknown) {
746
+ return handleWorkflowExecutionError({
747
+ effects,
748
+ state: {
749
+ ...stateRef.current,
750
+ stepIndex: failingStepIndex,
751
+ },
752
+ doc,
753
+ signal,
754
+ err,
755
+ action: "execution",
756
+ runId,
757
+ });
758
+ }
759
+
760
+ if (signal.aborted) {
761
+ const firstActive = activeWaveSteps[0];
762
+ return handleTermination(
763
+ signal,
764
+ effects,
765
+ stateRef.current,
766
+ firstActive.stepIndex,
767
+ firstActive.step.name,
768
+ steps.length,
769
+ runId,
770
+ );
771
+ }
772
+
773
+ const processedStepIndices = new Set<number>();
774
+ for (const item of activeWaveSteps) {
775
+ if (processedStepIndices.has(item.stepIndex)) continue;
776
+ processedStepIndices.add(item.stepIndex);
777
+
778
+ const stepItems = waveResults.filter(
779
+ (r) => r.stepIndex === item.stepIndex,
780
+ );
781
+ const isForeach = item.step.foreach !== undefined;
782
+
783
+ if (isForeach) {
784
+ if (item.step.output) {
785
+ const collected = stepItems.map((r) => r.subagentResult.outputText);
786
+ effects.recordOutput(
787
+ item.stepIndex,
788
+ item.step.output,
789
+ JSON.stringify(collected),
790
+ "list",
791
+ undefined,
792
+ runId,
793
+ );
794
+ outputs[item.step.output] = collected;
795
+ } else if (item.step.outputs !== undefined) {
796
+ for (const name of Object.keys(item.step.outputs)) {
797
+ const collectedValues: string[] = [];
798
+ for (const r of stepItems) {
799
+ if (!isRecord(r.subagentResult.structured)) {
800
+ return handleExecutionFailure(
801
+ effects,
802
+ { ...stateRef.current, stepIndex: item.stepIndex },
803
+ "execution",
804
+ new Error(
805
+ `Step ${item.stepIndex + 1} subagent failed to produce required structured outputs`,
806
+ ),
807
+ steps.length,
808
+ runId,
809
+ );
810
+ }
811
+ const val = r.subagentResult.structured[name];
812
+ if (typeof val !== "string" || val.length === 0) {
813
+ return handleExecutionFailure(
814
+ effects,
815
+ { ...stateRef.current, stepIndex: item.stepIndex },
816
+ "execution",
817
+ new Error(
818
+ `Step ${item.stepIndex + 1} subagent structured output '${name}' is missing or empty`,
819
+ ),
820
+ steps.length,
821
+ runId,
822
+ );
823
+ }
824
+ collectedValues.push(val);
825
+ }
826
+ effects.recordOutput(
827
+ item.stepIndex,
828
+ name,
829
+ JSON.stringify(collectedValues),
830
+ "list",
831
+ undefined,
832
+ runId,
833
+ );
834
+ outputs[name] = collectedValues;
835
+ }
836
+ }
837
+ stateRef.current = {
838
+ ...stateRef.current,
839
+ outputs: { ...outputs },
840
+ };
841
+ } else {
842
+ const singleResult = stepItems[0];
843
+ const subagentResult = singleResult.subagentResult;
844
+ const outputText = subagentResult.outputText;
845
+
846
+ if (
847
+ item.step.outputs !== undefined &&
848
+ Object.keys(item.step.outputs).length > 0
849
+ ) {
850
+ if (!isRecord(subagentResult.structured)) {
851
+ return handleExecutionFailure(
852
+ effects,
853
+ { ...stateRef.current, stepIndex: item.stepIndex },
854
+ "execution",
855
+ new Error(
856
+ `Step ${item.stepIndex + 1} subagent failed to produce required structured outputs`,
857
+ ),
858
+ steps.length,
859
+ runId,
860
+ );
861
+ }
862
+
863
+ const structured = subagentResult.structured;
864
+ const pendingStringOutputs: Array<{ name: string; val: string }> =
865
+ [];
866
+ for (const [name, def] of Object.entries(item.step.outputs)) {
867
+ const val = structured[name];
868
+ if (typeof val !== "string" || val.length === 0) {
869
+ return handleExecutionFailure(
870
+ effects,
871
+ { ...stateRef.current, stepIndex: item.stepIndex },
872
+ "execution",
873
+ new Error(
874
+ `Step ${item.stepIndex + 1} subagent structured output '${name}' is missing or empty`,
875
+ ),
876
+ steps.length,
877
+ runId,
878
+ );
879
+ }
880
+
881
+ if (def.type === "string") {
882
+ pendingStringOutputs.push({ name, val });
883
+ } else {
884
+ const expectedResolved = item.resolvedOutputPaths[name];
885
+ if (path.resolve(val) !== path.resolve(expectedResolved)) {
886
+ return handleExecutionFailure(
887
+ effects,
888
+ { ...stateRef.current, stepIndex: item.stepIndex },
889
+ "execution",
890
+ new Error(
891
+ `Step ${item.stepIndex + 1} subagent file output '${name}' returned path '${val}', expected '${expectedResolved}'`,
892
+ ),
893
+ steps.length,
894
+ runId,
895
+ );
896
+ }
897
+ }
898
+ }
899
+
900
+ for (const [name, def] of Object.entries(item.step.outputs)) {
901
+ if (def.type === "file") {
902
+ const resolved = item.resolvedOutputPaths[name];
903
+ const exists = await effects.checkFileWritten(resolved);
904
+ if (!exists) {
905
+ return handleExecutionFailure(
906
+ effects,
907
+ { ...stateRef.current, stepIndex: item.stepIndex },
908
+ "execution",
909
+ new Error(
910
+ `Step ${item.stepIndex + 1} subagent output verification failed: declared outputs were missing or unwritten`,
911
+ ),
912
+ steps.length,
913
+ runId,
914
+ );
915
+ }
916
+ }
917
+ }
918
+
919
+ for (const { name, val } of pendingStringOutputs) {
920
+ effects.recordOutput(
921
+ item.stepIndex,
922
+ name,
923
+ val,
924
+ "string",
925
+ undefined,
926
+ runId,
927
+ );
928
+ outputs[name] = val;
929
+ }
930
+
931
+ for (const [name, def] of Object.entries(item.step.outputs)) {
932
+ if (def.type === "file") {
933
+ const resolved = item.resolvedOutputPaths[name];
934
+ effects.recordOutput(
935
+ item.stepIndex,
936
+ name,
937
+ resolved,
938
+ def.type,
939
+ def.base,
940
+ runId,
941
+ );
942
+ outputs[name] = resolved;
943
+ }
944
+ }
945
+
946
+ stateRef.current = {
947
+ ...stateRef.current,
948
+ outputs: { ...outputs },
949
+ };
950
+ } else if (item.effect.output) {
951
+ effects.recordOutput(
952
+ item.stepIndex,
953
+ item.effect.output,
954
+ outputText,
955
+ "string",
956
+ undefined,
957
+ runId,
958
+ );
959
+ outputs[item.effect.output] = outputText;
960
+ stateRef.current = {
961
+ ...stateRef.current,
962
+ outputs: { ...outputs },
963
+ };
964
+ }
965
+ }
966
+ }
967
+
968
+ const lastActive = activeWaveSteps[activeWaveSteps.length - 1];
969
+ if (lastActive.effect.gate !== undefined) {
970
+ const pauseTransition = applyGatePause(
971
+ state,
972
+ lastActive.effect.gate,
973
+ lastActive.effect.stepLabel,
974
+ );
975
+ state = {
976
+ ...pauseTransition.nextState,
977
+ stepIndex: lastActive.stepIndex,
978
+ outputs: { ...outputs },
979
+ };
980
+ stateRef.current = state;
981
+ effects.emit({
982
+ action: "state",
983
+ ...state,
984
+ runId,
985
+ });
986
+ effects.emit({
987
+ action: "step",
988
+ id: `wf-step-${runId}-${lastActive.stepIndex}-gate`,
989
+ stepIndex: lastActive.stepIndex,
990
+ label: `Paused at gate: ${lastActive.effect.gate}`,
991
+ kind: "success",
992
+ runId,
993
+ });
994
+ return {
995
+ kind: "success",
996
+ text: `Workflow paused at gate: "${lastActive.effect.gate}". Resume with /wf-resume`,
997
+ };
998
+ }
999
+
1000
+ state = {
1001
+ ...state,
1002
+ stepIndex: waveEnd,
1003
+ status: "running",
1004
+ outputs: { ...outputs },
1005
+ };
1006
+ stateRef.current = state;
1007
+ if (state.stepIndex < steps.length) {
1008
+ effects.emit({
1009
+ action: "state",
1010
+ ...state,
1011
+ runId,
1012
+ });
1013
+ }
1014
+ continue;
1015
+ }
1016
+
1017
+ const resolvedOutputPaths = resolveStepOutputFilePaths(
1018
+ step.kind === "prompt" ? step.outputs : undefined,
1019
+ invocation.resolvedArgs,
1020
+ outputs,
1021
+ effects,
1022
+ );
1023
+
1024
+ const transition = computeStepTransition({
1025
+ doc,
1026
+ invocation,
1027
+ state,
1028
+ instructions: pendingInstructions,
1029
+ outputs,
1030
+ resolvedOutputPaths,
1031
+ });
1032
+
1033
+ if (transition.effect.type === "skip") {
1034
+ state = transition.nextState;
1035
+ stateRef.current = state;
1036
+ if (state.stepIndex < steps.length) {
1037
+ effects.emit({
1038
+ action: "state",
1039
+ ...state,
1040
+ runId,
1041
+ });
1042
+ }
1043
+ continue;
1044
+ }
1045
+
1046
+ if (transition.effect.type === "prompt") {
1047
+ pendingInstructions = undefined;
1048
+ const { effect, nextState } = transition;
1049
+ effects.emit({
1050
+ action: "step",
1051
+ id: `wf-step-${runId}-${currentStepIndex}`,
1052
+ stepIndex: currentStepIndex,
1053
+ label: effect.stepLabel,
1054
+ kind: "success",
1055
+ runId,
1056
+ });
1057
+
1058
+ await effects.dispatchPrompt(effect);
1059
+
1060
+ if (signal.aborted) {
1061
+ return handleTermination(
1062
+ signal,
1063
+ effects,
1064
+ stateRef.current,
1065
+ currentStepIndex,
1066
+ effect.stepLabel,
1067
+ steps.length,
1068
+ runId,
1069
+ );
1070
+ }
1071
+
1072
+ if (
1073
+ step.kind === "prompt" &&
1074
+ step.outputs !== undefined &&
1075
+ Object.keys(step.outputs).length > 0
1076
+ ) {
1077
+ const declaredOutputs = step.outputs;
1078
+ const verifiedValues: Record<string, string | readonly string[]> = {};
1079
+ let allVerified = false;
1080
+
1081
+ for (let attempt = 1; attempt <= 3; attempt++) {
1082
+ const missing: OutputRetryMissingItem[] = [];
1083
+ for (const [name, def] of Object.entries(declaredOutputs)) {
1084
+ if (verifiedValues[name] !== undefined) {
1085
+ continue;
1086
+ }
1087
+ if (def.type === "file") {
1088
+ const resolved = resolvedOutputPaths[name];
1089
+ const exists = await effects.checkFileWritten(resolved);
1090
+ if (exists) {
1091
+ verifiedValues[name] = resolved;
1092
+ } else {
1093
+ missing.push({ name, type: "file", resolvedPath: resolved });
1094
+ }
1095
+ } else if (def.type === "list") {
1096
+ const captured = effects.getCapturedOutput(
1097
+ currentStepIndex,
1098
+ name,
1099
+ );
1100
+ if (captured !== undefined) {
1101
+ const parsed = parseListOutput(name, captured, def);
1102
+ if (parsed.kind === "success") {
1103
+ verifiedValues[name] = parsed.value;
1104
+ } else {
1105
+ missing.push({ name, type: "list" });
1106
+ }
1107
+ } else {
1108
+ missing.push({ name, type: "list" });
1109
+ }
1110
+ } else {
1111
+ const captured = effects.getCapturedOutput(
1112
+ currentStepIndex,
1113
+ name,
1114
+ );
1115
+ if (captured !== undefined) {
1116
+ verifiedValues[name] = captured;
1117
+ } else {
1118
+ missing.push({ name, type: "string" });
1119
+ }
1120
+ }
1121
+ }
1122
+
1123
+ if (missing.length === 0) {
1124
+ allVerified = true;
1125
+ break;
1126
+ }
1127
+
1128
+ if (attempt < 3) {
1129
+ const stepName = interpolateTemplate(
1130
+ step.name,
1131
+ invocation.resolvedArgs,
1132
+ outputs,
1133
+ );
1134
+ const retryPromptText = formatOutputRetryPrompt({
1135
+ stepIndex: currentStepIndex,
1136
+ totalSteps: steps.length,
1137
+ stepName,
1138
+ missingOutputs: missing,
1139
+ attempt,
1140
+ });
1141
+ await effects.dispatchPrompt({
1142
+ type: "prompt",
1143
+ promptText: retryPromptText,
1144
+ stepLabel: `${effect.stepLabel} (Output Retry ${attempt}/3)`,
1145
+ });
1146
+ if (signal.aborted) {
1147
+ return handleTermination(
1148
+ signal,
1149
+ effects,
1150
+ stateRef.current,
1151
+ currentStepIndex,
1152
+ effect.stepLabel,
1153
+ steps.length,
1154
+ runId,
1155
+ );
1156
+ }
1157
+ }
1158
+ }
1159
+
1160
+ if (!allVerified) {
1161
+ return handleExecutionFailure(
1162
+ effects,
1163
+ stateRef.current,
1164
+ "execution",
1165
+ new Error(
1166
+ `Step ${currentStepIndex + 1} output verification failed after 3 attempts`,
1167
+ ),
1168
+ steps.length,
1169
+ runId,
1170
+ );
1171
+ }
1172
+
1173
+ for (const [name, def] of Object.entries(declaredOutputs)) {
1174
+ const val = verifiedValues[name];
1175
+ if (def.type === "file") {
1176
+ // type-safe: verifiedValues[name] for def.type === "file" is guaranteed to be a string resolved path
1177
+ effects.recordOutput(
1178
+ currentStepIndex,
1179
+ name,
1180
+ val as string,
1181
+ def.type,
1182
+ def.base,
1183
+ runId,
1184
+ );
1185
+ }
1186
+ outputs[name] = val;
1187
+ }
1188
+ stateRef.current = {
1189
+ ...stateRef.current,
1190
+ outputs: { ...outputs },
1191
+ };
1192
+ }
1193
+
1194
+ const hasOutputs = Object.keys(outputs).length > 0;
1195
+ if (effect.gate !== undefined) {
1196
+ const pauseTransition = applyGatePause(
1197
+ state,
1198
+ effect.gate,
1199
+ effect.stepLabel,
1200
+ );
1201
+ state = {
1202
+ ...pauseTransition.nextState,
1203
+ ...(hasOutputs ? { outputs } : {}),
1204
+ };
1205
+ stateRef.current = state;
1206
+ effects.emit({
1207
+ action: "state",
1208
+ ...state,
1209
+ runId,
1210
+ });
1211
+ effects.emit({
1212
+ action: "step",
1213
+ id: `wf-step-${runId}-${currentStepIndex}-gate`,
1214
+ stepIndex: currentStepIndex,
1215
+ label: `Paused at gate: ${effect.gate}`,
1216
+ kind: "success",
1217
+ runId,
1218
+ });
1219
+ return {
1220
+ kind: "success",
1221
+ text: `Workflow paused at gate: "${effect.gate}". Resume with /wf-resume`,
1222
+ };
1223
+ }
1224
+
1225
+ state = {
1226
+ ...nextState,
1227
+ ...(hasOutputs ? { outputs } : {}),
1228
+ };
1229
+ stateRef.current = state;
1230
+ } else {
1231
+ // type is narrowed to "print" during step loop transitions
1232
+ const effect = transition.effect as Extract<
1233
+ typeof transition.effect,
1234
+ { type: "print" }
1235
+ >;
1236
+ effects.emit({
1237
+ action: "print",
1238
+ id: `wf-print-${runId}-${currentStepIndex}`,
1239
+ text: effect.text,
1240
+ runId,
1241
+ });
1242
+ if (signal.aborted) {
1243
+ return handleTermination(
1244
+ signal,
1245
+ effects,
1246
+ stateRef.current,
1247
+ currentStepIndex,
1248
+ steps[currentStepIndex].name,
1249
+ steps.length,
1250
+ runId,
1251
+ );
1252
+ }
1253
+ const hasOutputs = Object.keys(outputs).length > 0;
1254
+ state = {
1255
+ ...transition.nextState,
1256
+ ...(hasOutputs ? { outputs } : {}),
1257
+ };
1258
+ stateRef.current = state;
1259
+ }
1260
+
1261
+ if (state.stepIndex < steps.length) {
1262
+ effects.emit({ action: "state", ...state, runId });
1263
+ }
1264
+ }
1265
+
1266
+ return completeWorkflow(effects, steps.length, outputs, runId);
1267
+ }
1268
+
1269
+ /**
1270
+ * Loads and parses a workflow document from effects, returning the parsed document or an error CommandResult.
1271
+ */
1272
+ async function loadAndParseWorkflow(
1273
+ targetPath: string,
1274
+ effects: WorkflowEffectContext,
1275
+ ): Promise<{ doc: WorkflowDocument } | CommandErrorResult> {
1276
+ let content: string;
1277
+ try {
1278
+ content = await effects.readWorkflow(targetPath);
1279
+ } catch (err: unknown) {
1280
+ const message = err instanceof Error ? err.message : String(err);
1281
+ return {
1282
+ kind: "error",
1283
+ text: `Failed to load workflow '${targetPath}': ${message}`,
1284
+ };
1285
+ }
1286
+
1287
+ const docStep = runValidationStep(
1288
+ () => parseWorkflowDocument(content),
1289
+ "Failed to parse workflow",
1290
+ targetPath,
1291
+ );
1292
+ if ("kind" in docStep) {
1293
+ return docStep;
1294
+ }
1295
+ return { doc: docStep.result };
1296
+ }
1297
+
1298
+ /**
1299
+ * Result of loading, argument resolution, and AST/runtime validation.
1300
+ */
1301
+ interface WorkflowValidationSuccess {
1302
+ readonly kind: "valid";
1303
+ readonly doc: WorkflowDocument;
1304
+ readonly targetPath: string;
1305
+ readonly rawInput: string;
1306
+ readonly resolvedArgs?: Record<string, string>;
1307
+ }
1308
+
1309
+ /**
1310
+ * Validates subagent step configurations against the live environment.
1311
+ * CONTRACT:
1312
+ * - Inputs: WorkflowDocument, effects context, targetPath, optional arguments, optional AbortSignal.
1313
+ * - Outputs: Formatted error message string on failure, or undefined if valid.
1314
+ */
1315
+ async function validateWorkflowSubagents(
1316
+ doc: WorkflowDocument,
1317
+ effects: WorkflowEffectContext,
1318
+ targetPath: string,
1319
+ args?: Record<string, string>,
1320
+ signal?: AbortSignal,
1321
+ ): Promise<string | undefined> {
1322
+ const effectiveArgs: Record<string, string> = { ...(args ?? {}) };
1323
+ if (args === undefined) {
1324
+ for (const [key, def] of Object.entries(doc.args)) {
1325
+ if (def.default !== undefined) {
1326
+ effectiveArgs[key] = String(def.default);
1327
+ }
1328
+ }
1329
+ }
1330
+
1331
+ for (let i = 0; i < doc.steps.length; i++) {
1332
+ const step = doc.steps[i];
1333
+ if (step.kind !== "subagent") continue;
1334
+
1335
+ let configToValidate: SubagentConfig;
1336
+ try {
1337
+ if (step.rawSubagent) {
1338
+ const interpolated = interpolateTemplate(
1339
+ step.rawSubagent,
1340
+ effectiveArgs,
1341
+ );
1342
+ if (interpolated.includes("{{")) continue;
1343
+ const parsed = parseSubagentShorthand(interpolated);
1344
+ configToValidate = normalizeSubagentConfig(parsed);
1345
+ } else {
1346
+ const interpolatedConfig = interpolateSubagentConfig(
1347
+ step.config,
1348
+ effectiveArgs,
1349
+ );
1350
+ if (
1351
+ Object.values(interpolatedConfig).some(
1352
+ (v) => typeof v === "string" && v.includes("{{"),
1353
+ )
1354
+ ) {
1355
+ continue;
1356
+ }
1357
+ configToValidate = interpolatedConfig;
1358
+ }
1359
+ } catch (err: unknown) {
1360
+ if (
1361
+ args === undefined &&
1362
+ String(err).includes("Unresolved workflow argument")
1363
+ ) {
1364
+ continue;
1365
+ }
1366
+ const message = err instanceof Error ? err.message : String(err);
1367
+ return `Validation error in workflow '${targetPath}': Subagent step ${i + 1} ('${step.name}'): ${message}`;
1368
+ }
1369
+
1370
+ const routeResult = await effects.validateSubagentRoute(
1371
+ configToValidate,
1372
+ signal,
1373
+ );
1374
+ if (!routeResult.valid) {
1375
+ return `Validation error in workflow '${targetPath}': Subagent step ${i + 1} ('${step.name}'): ${routeResult.message}`;
1376
+ }
1377
+ }
1378
+
1379
+ return undefined;
1380
+ }
1381
+
1382
+ /**
1383
+ * Loads, parses, resolves arguments, runs pure AST rules, and validates subagent routes.
1384
+ * CONTRACT:
1385
+ * - Inputs: rawInput string, effects context, options (requireArgs, usageText, optional signal).
1386
+ * - Outputs: WorkflowValidationSuccess or CommandErrorResult.
1387
+ */
1388
+ async function loadAndValidateWorkflowCore(
1389
+ rawInput: string,
1390
+ effects: WorkflowEffectContext,
1391
+ options: {
1392
+ requireArgs: boolean;
1393
+ usageText: string;
1394
+ signal?: AbortSignal;
1395
+ },
1396
+ ): Promise<WorkflowValidationSuccess | CommandErrorResult> {
1397
+ const parsed = parseInvocationInput(rawInput);
1398
+ if (!parsed.targetPath) {
1399
+ return { kind: "error", text: options.usageText };
1400
+ }
1401
+
1402
+ const loaded = await loadAndParseWorkflow(parsed.targetPath, effects);
1403
+ if ("kind" in loaded) {
1404
+ return loaded;
1405
+ }
1406
+ const doc = loaded.doc;
1407
+
1408
+ const hasExplicitArgs =
1409
+ Object.keys(parsed.explicitArgs).length > 0 ||
1410
+ parsed.implicitInstructions.length > 0;
1411
+
1412
+ let resolvedArgs: Record<string, string> | undefined;
1413
+
1414
+ if (hasExplicitArgs || options.requireArgs) {
1415
+ const argsStep = runValidationStep(
1416
+ () =>
1417
+ resolveWorkflowArgs({
1418
+ declarations: doc.args,
1419
+ explicitArgs: parsed.explicitArgs,
1420
+ implicitInstructions: parsed.implicitInstructions,
1421
+ }),
1422
+ "Argument error in workflow",
1423
+ parsed.targetPath,
1424
+ );
1425
+ if ("kind" in argsStep) {
1426
+ return argsStep;
1427
+ }
1428
+ resolvedArgs = argsStep.result;
1429
+ }
1430
+
1431
+ const validationErrors = validateWorkflow({ doc, args: resolvedArgs });
1432
+ if (validationErrors.length > 0) {
1433
+ return {
1434
+ kind: "error",
1435
+ text: formatValidationErrors(parsed.targetPath, validationErrors),
1436
+ };
1437
+ }
1438
+
1439
+ const subagentError = await validateWorkflowSubagents(
1440
+ doc,
1441
+ effects,
1442
+ parsed.targetPath,
1443
+ resolvedArgs,
1444
+ options.signal,
1445
+ );
1446
+ if (subagentError) {
1447
+ return {
1448
+ kind: "error",
1449
+ text: subagentError,
1450
+ };
1451
+ }
1452
+
1453
+ return {
1454
+ kind: "valid",
1455
+ doc,
1456
+ targetPath: parsed.targetPath,
1457
+ rawInput,
1458
+ resolvedArgs,
1459
+ };
1460
+ }
1461
+
1462
+ /**
1463
+ * Validates a workflow invocation input, reading and parsing the file and arguments.
1464
+ * CONTRACT:
1465
+ * - Input: targetPath string, effects context, optional runId, optional signal.
1466
+ * - Output: Promise resolving to ValidatedWorkflow or error CommandResult.
1467
+ * - Errors: returns error CommandResult if session ID missing, file not found, or syntax invalid.
1468
+ */
1469
+ export async function validateWorkflowInvocation(
1470
+ targetPath: string,
1471
+ effects: WorkflowEffectContext,
1472
+ runId?: string,
1473
+ signal?: AbortSignal,
1474
+ ): Promise<ValidatedWorkflow | CommandErrorResult> {
1475
+ const sessionId = effects.sessionId;
1476
+ if (!sessionId) {
1477
+ return {
1478
+ kind: "error",
1479
+ text: "Workflow execution failed: agent session ID is required",
1480
+ };
1481
+ }
1482
+
1483
+ const result = await loadAndValidateWorkflowCore(targetPath, effects, {
1484
+ requireArgs: true,
1485
+ usageText: "Usage: /wf <workflow.yaml>",
1486
+ signal,
1487
+ });
1488
+ if (result.kind === "error") {
1489
+ return result;
1490
+ }
1491
+
1492
+ const invocation: WorkflowInvocation = {
1493
+ targetPath: result.targetPath,
1494
+ rawInput: targetPath,
1495
+ resolvedArgs: result.resolvedArgs ?? {},
1496
+ runId: runId ?? crypto.randomUUID(),
1497
+ };
1498
+
1499
+ const state: WorkflowState = {
1500
+ stepIndex: 0,
1501
+ status: "running",
1502
+ };
1503
+
1504
+ return {
1505
+ kind: "valid",
1506
+ doc: result.doc,
1507
+ invocation,
1508
+ state,
1509
+ };
1510
+ }
1511
+
1512
+ /**
1513
+ * Validates a workflow file and optional invocation arguments without executing it.
1514
+ * CONTRACT:
1515
+ * - Input: rawInput string containing workflow target path and optional arguments, effects context.
1516
+ * - Output: Promise resolving to CommandResult (success with summary or error with diagnostics).
1517
+ * - Invariant: Zero state mutations, zero session events, does not require active session ID or idle workflow runner.
1518
+ */
1519
+ export async function validateWorkflowTarget(
1520
+ rawInput: string,
1521
+ effects: WorkflowEffectContext,
1522
+ ): Promise<CommandResult> {
1523
+ const result = await loadAndValidateWorkflowCore(rawInput, effects, {
1524
+ requireArgs: false,
1525
+ usageText: "Usage: /wf-validate <workflow.yaml> [key=value ...]",
1526
+ });
1527
+ if (result.kind === "error") {
1528
+ return result;
1529
+ }
1530
+
1531
+ return {
1532
+ kind: "success",
1533
+ text: formatValidationSummary(
1534
+ result.targetPath,
1535
+ result.doc,
1536
+ result.resolvedArgs,
1537
+ ),
1538
+ };
1539
+ }
1540
+
1541
+ /**
1542
+ * Executes a pre-validated workflow, emitting initialization events and driving steps.
1543
+ * CONTRACT:
1544
+ * - Input: validated workflow descriptor, effects context, optional signal.
1545
+ * - Output: Promise resolving to CommandResult.
1546
+ */
1547
+ export async function executeValidatedWorkflow(
1548
+ validated: ValidatedWorkflow,
1549
+ effects: WorkflowEffectContext,
1550
+ signal?: AbortSignal,
1551
+ ): Promise<CommandResult> {
1552
+ const activeRun = foldWorkflowState(effects.snapshotEvents());
1553
+ if (activeRun !== null && activeRun.state.status === "running") {
1554
+ return {
1555
+ kind: "error",
1556
+ text: `Cannot start workflow: '${activeRun.workflow.name ?? activeRun.invocation.targetPath}' is already running`,
1557
+ };
1558
+ }
1559
+ return withWorkflowExecution(effects, () =>
1560
+ executeValidatedWorkflowDirect(validated, effects, signal),
1561
+ );
1562
+ }
1563
+
1564
+ async function executeValidatedWorkflowDirect(
1565
+ validated: ValidatedWorkflow,
1566
+ effects: WorkflowEffectContext,
1567
+ signal?: AbortSignal,
1568
+ ): Promise<CommandResult> {
1569
+ const { doc, invocation, state } = validated;
1570
+ const runId = invocation.runId;
1571
+ const workflowAbortController = new AbortController();
1572
+ const combinedSignal = signal
1573
+ ? AbortSignal.any([signal, workflowAbortController.signal])
1574
+ : workflowAbortController.signal;
1575
+ const cleanupAbort = effects.watchAbort(workflowAbortController);
1576
+
1577
+ const stateRef = { current: state };
1578
+ try {
1579
+ const rawTitle = doc.title ?? doc.name;
1580
+ if (rawTitle && !effects.hasTitle()) {
1581
+ const sessionTitle = interpolateTemplate(
1582
+ rawTitle,
1583
+ invocation.resolvedArgs,
1584
+ );
1585
+ if (sessionTitle.trim().length > 0) {
1586
+ effects.setTitle(sessionTitle);
1587
+ }
1588
+ }
1589
+
1590
+ effects.emit({
1591
+ action: "init",
1592
+ workflow: doc,
1593
+ invocation,
1594
+ runId,
1595
+ });
1596
+
1597
+ await effects.whenIdle();
1598
+ if (combinedSignal.aborted) {
1599
+ return handleTermination(
1600
+ combinedSignal,
1601
+ effects,
1602
+ stateRef.current,
1603
+ stateRef.current.stepIndex,
1604
+ doc.steps[stateRef.current.stepIndex].name,
1605
+ doc.steps.length,
1606
+ runId,
1607
+ );
1608
+ }
1609
+
1610
+ effects.setStatus("running");
1611
+ return await runWorkflowSteps({
1612
+ effects,
1613
+ doc,
1614
+ invocation,
1615
+ stateRef,
1616
+ signal: combinedSignal,
1617
+ });
1618
+ } catch (err: unknown) {
1619
+ return handleWorkflowExecutionError({
1620
+ effects,
1621
+ state: stateRef.current,
1622
+ doc,
1623
+ signal: combinedSignal,
1624
+ err,
1625
+ action: "execution",
1626
+ runId,
1627
+ });
1628
+ } finally {
1629
+ cleanupAbort();
1630
+ effects.setStatus("idle");
1631
+ }
1632
+ }
1633
+
1634
+ /**
1635
+ * Loads and initiates a workflow YAML file, executing steps sequentially.
1636
+ * CONTRACT:
1637
+ * - Input: effects context, targetPath string, and optional signal.
1638
+ * - Output: Promise resolving to CommandResult (success, gate pause, or abort error).
1639
+ * - Errors: returns error CommandResult if session ID missing, file not found, or syntax invalid.
1640
+ */
1641
+ export async function executeWorkflow({
1642
+ effects,
1643
+ targetPath,
1644
+ signal,
1645
+ runId,
1646
+ }: {
1647
+ effects: WorkflowEffectContext;
1648
+ targetPath: string;
1649
+ signal?: AbortSignal;
1650
+ runId?: string;
1651
+ }): Promise<CommandResult> {
1652
+ const validated = await validateWorkflowInvocation(
1653
+ targetPath,
1654
+ effects,
1655
+ runId,
1656
+ signal,
1657
+ );
1658
+ if (validated.kind === "error") {
1659
+ return validated;
1660
+ }
1661
+ return executeValidatedWorkflow(validated, effects, signal);
1662
+ }
1663
+
1664
+ /**
1665
+ * Resumes an interrupted or gate-paused workflow from session event log.
1666
+ * CONTRACT:
1667
+ * - Inputs: effects context, optional signal, and additional resumption instructions.
1668
+ * - Outputs: Promise resolving to CommandResult (success or error).
1669
+ * - Throws: None (errors returned as CommandResult error objects).
1670
+ */
1671
+ export function resumeWorkflow(options: {
1672
+ effects: WorkflowEffectContext;
1673
+ signal?: AbortSignal;
1674
+ instructions?: string;
1675
+ }): Promise<CommandResult> {
1676
+ return withWorkflowExecution(options.effects, () =>
1677
+ resumeWorkflowDirect(options),
1678
+ );
1679
+ }
1680
+
1681
+ /**
1682
+ * Purpose: Acknowledges a valid resume without retaining the submitting UI request.
1683
+ * Contract:
1684
+ * - Inputs: session effects, additional instructions, and the admission request signal.
1685
+ * - Outputs: validation errors or acknowledgement before resumed execution finishes.
1686
+ * - Throws / Errors: unexpected background failures are logged.
1687
+ */
1688
+ export async function requestWorkflowResume(
1689
+ effects: WorkflowEffectContext,
1690
+ instructions: string,
1691
+ signal: AbortSignal,
1692
+ ): Promise<CommandResult> {
1693
+ if (executingSessions.has(effects.sessionId)) {
1694
+ return {
1695
+ kind: "error",
1696
+ text: "A workflow is already executing in this session",
1697
+ };
1698
+ }
1699
+ const prepared = await prepareWorkflowResume(effects);
1700
+ if (prepared.kind === "error") return prepared;
1701
+ signal.throwIfAborted();
1702
+ if (executingSessions.has(effects.sessionId)) {
1703
+ return {
1704
+ kind: "error",
1705
+ text: "A workflow is already executing in this session",
1706
+ };
1707
+ }
1708
+ void withWorkflowExecution(effects, () =>
1709
+ executeWorkflowResume({ effects, instructions, run: prepared.run }),
1710
+ ).catch((error: unknown) => {
1711
+ effects.logInfo(`Workflow resume failed: ${extractErrorMessage(error)}`);
1712
+ });
1713
+ return { kind: "success", text: "Workflow resume accepted" };
1714
+ }
1715
+
1716
+ async function prepareWorkflowResume(
1717
+ effects: WorkflowEffectContext,
1718
+ ): Promise<
1719
+ { readonly kind: "ready"; readonly run: WorkflowRun } | CommandErrorResult
1720
+ > {
1721
+ const sessionError = await ensureIdleSession(effects, "resume");
1722
+ if (sessionError) {
1723
+ return sessionError;
1724
+ }
1725
+
1726
+ const run = foldWorkflowState(effects.snapshotEvents());
1727
+ if (!run) {
1728
+ return {
1729
+ kind: "error",
1730
+ text: "No interrupted workflow found to resume",
1731
+ };
1732
+ }
1733
+ if (run.state.status === "completed") {
1734
+ return {
1735
+ kind: "error",
1736
+ text: "Workflow has already completed",
1737
+ };
1738
+ }
1739
+
1740
+ return { kind: "ready", run };
1741
+ }
1742
+
1743
+ async function resumeWorkflowDirect(options: {
1744
+ effects: WorkflowEffectContext;
1745
+ signal?: AbortSignal;
1746
+ instructions?: string;
1747
+ }): Promise<CommandResult> {
1748
+ const prepared = await prepareWorkflowResume(options.effects);
1749
+ if (prepared.kind === "error") return prepared;
1750
+ return executeWorkflowResume({ ...options, run: prepared.run });
1751
+ }
1752
+
1753
+ async function executeWorkflowResume({
1754
+ effects,
1755
+ signal,
1756
+ instructions,
1757
+ run,
1758
+ }: {
1759
+ effects: WorkflowEffectContext;
1760
+ signal?: AbortSignal;
1761
+ instructions?: string;
1762
+ run: WorkflowRun;
1763
+ }): Promise<CommandResult> {
1764
+ const { workflow: doc, invocation, state } = run;
1765
+ const isInterruptedPause =
1766
+ state.status === "paused" && state.pauseReason === "interrupted";
1767
+ const nextStepIndex =
1768
+ state.status === "paused" && !isInterruptedPause
1769
+ ? state.stepIndex + 1
1770
+ : state.stepIndex;
1771
+
1772
+ const workflowAbortController = new AbortController();
1773
+ const combinedSignal = signal
1774
+ ? AbortSignal.any([signal, workflowAbortController.signal])
1775
+ : workflowAbortController.signal;
1776
+ const cleanupAbort = effects.watchAbort(workflowAbortController);
1777
+
1778
+ const { error: _error, ...cleanState } = state;
1779
+ const resumeState: WorkflowState = {
1780
+ ...cleanState,
1781
+ stepIndex: nextStepIndex,
1782
+ };
1783
+ const stateRef = { current: resumeState };
1784
+
1785
+ try {
1786
+ if (nextStepIndex >= doc.steps.length) {
1787
+ return completeWorkflow(
1788
+ effects,
1789
+ doc.steps.length,
1790
+ state.outputs,
1791
+ invocation.runId,
1792
+ );
1793
+ }
1794
+
1795
+ if (combinedSignal.aborted) {
1796
+ return handleTermination(
1797
+ combinedSignal,
1798
+ effects,
1799
+ stateRef.current,
1800
+ nextStepIndex,
1801
+ doc.steps[nextStepIndex].name,
1802
+ doc.steps.length,
1803
+ invocation.runId,
1804
+ );
1805
+ }
1806
+
1807
+ const { pauseReason: _pauseReason, ...runningState } = cleanState;
1808
+ effects.emit({
1809
+ action: "state",
1810
+ ...runningState,
1811
+ stepIndex: nextStepIndex,
1812
+ status: "running",
1813
+ runId: invocation.runId,
1814
+ });
1815
+
1816
+ effects.logInfo(
1817
+ `Resuming workflow '${doc.name ?? invocation.targetPath}' at step ${nextStepIndex + 1}/${doc.steps.length}${instructions ? ` with instructions: ${instructions}` : ""}`,
1818
+ );
1819
+
1820
+ effects.setStatus("running");
1821
+ return await runWorkflowSteps({
1822
+ effects,
1823
+ doc,
1824
+ invocation,
1825
+ stateRef,
1826
+ signal: combinedSignal,
1827
+ instructions: instructions ? instructions.trim() : undefined,
1828
+ });
1829
+ } catch (err: unknown) {
1830
+ return handleWorkflowExecutionError({
1831
+ effects,
1832
+ state: stateRef.current,
1833
+ doc,
1834
+ signal: combinedSignal,
1835
+ err,
1836
+ action: "resume",
1837
+ runId: invocation.runId,
1838
+ });
1839
+ } finally {
1840
+ cleanupAbort();
1841
+ effects.setStatus("idle");
1842
+ }
1843
+ }
1844
+
1845
+ /**
1846
+ * Purpose: Discards an active, paused, or interrupted workflow, marking it aborted.
1847
+ * Contract:
1848
+ * - Inputs: effects context for the target session.
1849
+ * - Outputs: Promise resolving to CommandResult (success or error).
1850
+ * - Throws: None.
1851
+ */
1852
+ export function discardWorkflow(options: {
1853
+ effects: WorkflowEffectContext;
1854
+ }): Promise<CommandResult> {
1855
+ return withWorkflowExecution(options.effects, () =>
1856
+ discardWorkflowDirect(options),
1857
+ );
1858
+ }
1859
+
1860
+ async function discardWorkflowDirect({
1861
+ effects,
1862
+ }: {
1863
+ effects: WorkflowEffectContext;
1864
+ }): Promise<CommandResult> {
1865
+ const sessionError = await ensureIdleSession(effects, "discard");
1866
+ if (sessionError) {
1867
+ return sessionError;
1868
+ }
1869
+
1870
+ const run = foldWorkflowState(effects.snapshotEvents());
1871
+ if (!run) {
1872
+ return {
1873
+ kind: "error",
1874
+ text: "No active workflow to discard",
1875
+ };
1876
+ }
1877
+ if (run.state.status === "running") {
1878
+ return {
1879
+ kind: "error",
1880
+ text: "Cannot discard an actively running workflow; stop execution first",
1881
+ };
1882
+ }
1883
+ if (run.state.status === "completed" || run.state.status === "aborted") {
1884
+ return {
1885
+ kind: "error",
1886
+ text: "Workflow is not active or has already ended",
1887
+ };
1888
+ }
1889
+
1890
+ const { workflow: doc, state, invocation } = run;
1891
+ const runId = invocation.runId;
1892
+ const stepName = `: ${doc.steps[state.stepIndex].name}`;
1893
+ const transition = applyAbort(state, doc.steps.length, false);
1894
+ effects.emit({
1895
+ action: "state",
1896
+ ...transition.nextState,
1897
+ runId,
1898
+ });
1899
+ effects.emit({
1900
+ action: "step",
1901
+ id: `wf-step-${runId}-${state.stepIndex}-discarded`,
1902
+ stepIndex: state.stepIndex,
1903
+ label: `Workflow discarded at step ${state.stepIndex + 1} of ${doc.steps.length}${stepName}`,
1904
+ kind: "error",
1905
+ runId,
1906
+ });
1907
+ effects.logInfo(
1908
+ `Workflow '${doc.name ?? run.invocation.targetPath}' discarded by user at step ${state.stepIndex + 1}/${doc.steps.length}`,
1909
+ );
1910
+
1911
+ return {
1912
+ kind: "success",
1913
+ text: `Workflow discarded at step ${state.stepIndex + 1}/${doc.steps.length}`,
1914
+ };
1915
+ }
1916
+
1917
+ /**
1918
+ * Purpose: Lists and summarizes available workflows in local and common directories.
1919
+ * Contract:
1920
+ * - Inputs: WorkflowEffectContext instance.
1921
+ * - Outputs: Promise resolving to CommandResult ({ kind: "success", text: string }).
1922
+ * - Throws: None (errors handled gracefully).
1923
+ */
1924
+ export async function listWorkflows(
1925
+ effects: WorkflowEffectContext,
1926
+ ): Promise<CommandResult> {
1927
+ const [localFiles, commonFiles] = await Promise.all([
1928
+ effects.listWorkflowFiles("local"),
1929
+ effects.listWorkflowFiles("common"),
1930
+ ]);
1931
+
1932
+ const parseSummaries = (
1933
+ files: ReadonlyArray<{ readonly target: string; readonly content: string }>,
1934
+ ): WorkflowSummary[] => {
1935
+ const summaries: WorkflowSummary[] = [];
1936
+ for (const file of files) {
1937
+ const summary = parseWorkflowSummary(file.target, file.content);
1938
+ if (summary) {
1939
+ summaries.push(summary);
1940
+ }
1941
+ }
1942
+ return summaries;
1943
+ };
1944
+
1945
+ const localSummaries = parseSummaries(localFiles);
1946
+ const commonSummaries = parseSummaries(commonFiles);
1947
+
1948
+ return {
1949
+ kind: "success",
1950
+ text: formatWorkflowList([
1951
+ { title: "Local Workflows (.agents/wf)", workflows: localSummaries },
1952
+ { title: "Common Workflows (~/.agents/wf)", workflows: commonSummaries },
1953
+ ]),
1954
+ };
1955
+ }