@usearazzo/runner 1.0.1-alpha.33 → 1.0.1-alpha.35

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 (72) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/README.md +15 -1
  3. package/dist/arazzo-runner.browser.js +1516 -265
  4. package/dist/arazzo-runner.browser.min.js +1 -1
  5. package/package.json +64 -18
  6. package/src/ArazzoRunner.cjs +26 -3
  7. package/src/ArazzoRunner.mjs +26 -3
  8. package/src/client/OpenAPIOperationResponse.cjs +9 -0
  9. package/src/client/OpenAPIOperationResponse.mjs +9 -0
  10. package/src/document/APIDocument.cjs +53 -0
  11. package/src/document/APIDocument.mjs +53 -0
  12. package/src/errors/ExecutionError.cjs +2 -0
  13. package/src/errors/ExecutionError.mjs +2 -0
  14. package/src/executor/OpenAPIOperationExecutor.cjs +77 -6
  15. package/src/executor/OpenAPIOperationExecutor.mjs +77 -6
  16. package/src/executor/StepExecutor.cjs +16 -2
  17. package/src/executor/StepExecutor.mjs +16 -2
  18. package/src/executor/StepRetryRunner.cjs +5 -3
  19. package/src/executor/StepRetryRunner.mjs +5 -3
  20. package/src/executor/StepTransitionInterpreter.cjs +1 -1
  21. package/src/executor/StepTransitionInterpreter.mjs +1 -1
  22. package/src/executor/WorkflowCallStack.cjs +1 -1
  23. package/src/executor/WorkflowCallStack.mjs +1 -1
  24. package/src/executor/WorkflowExecutor.cjs +447 -89
  25. package/src/executor/WorkflowExecutor.mjs +447 -89
  26. package/src/index.cjs +21 -0
  27. package/src/index.mjs +4 -0
  28. package/src/observability/ArazzoRunnerEvent.cjs +5 -0
  29. package/src/observability/ArazzoRunnerEvent.mjs +1 -0
  30. package/src/observability/DocumentRegistryEvent.cjs +5 -0
  31. package/src/observability/DocumentRegistryEvent.mjs +1 -0
  32. package/src/observability/EventChannel.cjs +106 -0
  33. package/src/observability/EventChannel.mjs +98 -0
  34. package/src/observability/OpenAPIOperationEvent.cjs +5 -0
  35. package/src/observability/OpenAPIOperationEvent.mjs +1 -0
  36. package/src/observability/Redactor.cjs +215 -0
  37. package/src/observability/Redactor.mjs +210 -0
  38. package/src/observability/WorkflowExecutionEvent.cjs +5 -0
  39. package/src/observability/WorkflowExecutionEvent.mjs +1 -0
  40. package/src/observability/combineObservers.cjs +18 -0
  41. package/src/observability/combineObservers.mjs +12 -0
  42. package/src/observability/instrument.cjs +159 -0
  43. package/src/observability/instrument.mjs +144 -0
  44. package/src/observability/logging/LoggingObserver.cjs +177 -0
  45. package/src/observability/logging/LoggingObserver.mjs +172 -0
  46. package/src/observability/logging/index.cjs +13 -0
  47. package/src/observability/logging/index.mjs +1 -0
  48. package/src/observability/opentelemetry/ArazzoRunnerInstrumentation.cjs +321 -0
  49. package/src/observability/opentelemetry/ArazzoRunnerInstrumentation.mjs +313 -0
  50. package/src/observability/opentelemetry/index.cjs +13 -0
  51. package/src/observability/opentelemetry/index.mjs +1 -0
  52. package/src/observability/stream/EventStream.cjs +112 -0
  53. package/src/observability/stream/EventStream.mjs +107 -0
  54. package/src/observability/stream/index.cjs +13 -0
  55. package/src/observability/stream/index.mjs +1 -0
  56. package/src/registry/DocumentRegistry.cjs +27 -3
  57. package/src/registry/DocumentRegistry.mjs +27 -3
  58. package/src/registry/providers/ArazzoDocumentRegistryProvider.cjs +20 -0
  59. package/src/registry/providers/ArazzoDocumentRegistryProvider.mjs +21 -1
  60. package/src/registry/providers/DocumentRegistryProvider.cjs +14 -0
  61. package/src/registry/providers/DocumentRegistryProvider.mjs +14 -0
  62. package/src/registry/providers/OpenAPIDocumentRegistryProvider.cjs +27 -5
  63. package/src/registry/providers/OpenAPIDocumentRegistryProvider.mjs +27 -5
  64. package/src/version.cjs +9 -0
  65. package/src/version.mjs +3 -0
  66. package/types/observability/logging/LoggingObserver.d.ts +82 -0
  67. package/types/observability/logging/index.d.ts +2 -0
  68. package/types/observability/opentelemetry/ArazzoRunnerInstrumentation.d.ts +84 -0
  69. package/types/observability/opentelemetry/index.d.ts +2 -0
  70. package/types/observability/stream/EventStream.d.ts +68 -0
  71. package/types/observability/stream/index.d.ts +2 -0
  72. package/types/runner.d.ts +802 -5
@@ -9,6 +9,7 @@ exports.default = void 0;
9
9
  exports.settledResult = settledResult;
10
10
  var _apidomCore = require("@speclynx/apidom-core");
11
11
  var _ramdaAdjunct = require("ramda-adjunct");
12
+ var _shortUniqueId = _interopRequireDefault(require("short-unique-id"));
12
13
  var _apidomDatamodel = require("@speclynx/apidom-datamodel");
13
14
  var _apidomNsArazzo = require("@speclynx/apidom-ns-arazzo-1");
14
15
  var _RuntimeExpressionEvaluator = _interopRequireDefault(require("../expression/RuntimeExpressionEvaluator.cjs"));
@@ -21,10 +22,12 @@ var _StepExecutor = require("./StepExecutor.cjs");
21
22
  var _ArazzoWorkflowLocatorNormalizer = _interopRequireDefault(require("./ArazzoWorkflowLocatorNormalizer.cjs"));
22
23
  var _StepRetryRunner = _interopRequireDefault(require("./StepRetryRunner.cjs"));
23
24
  var _WorkflowCallStack = _interopRequireDefault(require("./WorkflowCallStack.cjs"));
25
+ var _instrument = require("../observability/instrument.cjs");
24
26
  var _StepTransitionInterpreter = _interopRequireWildcard(require("./StepTransitionInterpreter.cjs"));
25
27
  var _ExecutionError = _interopRequireDefault(require("../errors/ExecutionError.cjs"));
26
28
  var _ResolverError = _interopRequireDefault(require("../errors/ResolverError.cjs"));
27
29
  var _abort = require("./abort.cjs");
30
+ var _EventChannel = _interopRequireDefault(require("../observability/EventChannel.cjs"));
28
31
  /**
29
32
  * Options for the WorkflowExecutor.
30
33
  * @public
@@ -96,6 +99,12 @@ function settledResult(result) {
96
99
  * @internal
97
100
  */
98
101
 
102
+ /**
103
+ * How a step ran: its last attempt's outcome, the terminal action its retries
104
+ * resolved to, how many attempts it took, and where the run goes next.
105
+ * @internal
106
+ */
107
+
99
108
  /**
100
109
  * One completed `dependsOn` run, remembered with the inputs it was actually
101
110
  * given — see {@link RunScope.dependencyRuns}.
@@ -117,6 +126,14 @@ function settledResult(result) {
117
126
  * travel together into everything it delegates to.
118
127
  */
119
128
 
129
+ /**
130
+ * What every event of one workflow invocation shares.
131
+ */
132
+
133
+ /**
134
+ * What every step-scoped event of one step shares.
135
+ */
136
+
120
137
  /**
121
138
  * Executes an Arazzo workflow: the stateful loop that turns "run one step" into
122
139
  * "run a workflow".
@@ -162,6 +179,14 @@ class WorkflowExecutor {
162
179
  static #DEFAULT_MAX_STEPS = 1000;
163
180
  static #DEFAULT_MAX_WORKFLOW_DEPTH = 32;
164
181
  static #DEFAULT_NOW = () => performance.now();
182
+ /**
183
+ * Generates each run's `runId`: random rather than counted, so the events
184
+ * of runs in different processes stay apart once collected in one place.
185
+ * It needs no Web Crypto, which browsers offer only on secure pages.
186
+ */
187
+ static #RUN_IDS = new _shortUniqueId.default({
188
+ length: 12
189
+ });
165
190
  static #EXECUTE_OPTION_KEYS = new Set(['inputs', 'executeOptions', 'dependencyInputs', 'runDependencies', 'signal']);
166
191
  #document;
167
192
  #registry;
@@ -176,6 +201,8 @@ class WorkflowExecutor {
176
201
  #retryRunner;
177
202
  #interpreter = new _StepTransitionInterpreter.default();
178
203
  #workflowLocatorNormalizer;
204
+ // emits only while `hasObservers`, so an unobserved block builds no events
205
+ #events;
179
206
  constructor(options) {
180
207
  this.#document = options.document;
181
208
  this.#registry = options.registry;
@@ -184,6 +211,10 @@ class WorkflowExecutor {
184
211
  this.#maxSteps = options.maxSteps ?? WorkflowExecutor.#DEFAULT_MAX_STEPS;
185
212
  this.#maxWorkflowDepth = options.maxWorkflowDepth ?? WorkflowExecutor.#DEFAULT_MAX_WORKFLOW_DEPTH;
186
213
  this.#now = options.now ?? WorkflowExecutor.#DEFAULT_NOW;
214
+ this.#events = new _EventChannel.default({
215
+ observer: options.observer,
216
+ now: this.#now
217
+ });
187
218
  this.#stepExecutor = options.stepExecutor;
188
219
  this.#retryRunner = new _StepRetryRunner.default({
189
220
  sleep: options.sleep
@@ -207,7 +238,9 @@ class WorkflowExecutor {
207
238
  signal
208
239
  } = options;
209
240
  const executeOptions = this.#executeOptionsByName(options.executeOptions ?? {});
241
+ const runId = `run-${WorkflowExecutor.#RUN_IDS.randomUUID()}`;
210
242
  const scope = {
243
+ runId,
211
244
  // the signal is put into every step's opaque bag, because that bag is
212
245
  // how anything reaches the transport: the executor's own checks stop the
213
246
  // run at the next boundary, and this is what cancels the request already
@@ -216,7 +249,9 @@ class WorkflowExecutor {
216
249
  // leave the run walking on.
217
250
  executeOptions: (locator, step) => ({
218
251
  ...this.#executeOptionsFor(executeOptions, locator, step),
219
- signal
252
+ signal,
253
+ // set over any entry's own, like the signal: it names this run.
254
+ runId
220
255
  }),
221
256
  dependencyInputs: options.dependencyInputs ?? {},
222
257
  runDependencies: options.runDependencies ?? true,
@@ -334,18 +369,86 @@ class WorkflowExecutor {
334
369
  workflowId,
335
370
  callStack: nested
336
371
  });
337
- const workflow = await this.#resolveWorkflow(locator, scope);
338
- const state = new _WorkflowExecutionState.default({
339
- inputs
340
- });
372
+ const frame = {
373
+ runId: scope.runId,
374
+ workflowId,
375
+ path: nested.path
376
+ };
377
+ // extracted before `workflow:start`: a workflow its document does not
378
+ // define never starts, and the event can say where the one it runs is.
379
+ const extracted = this.#extractWorkflow(locator);
380
+ const location = locator.document.locationOf(extracted);
341
381
  const invocation = {
342
382
  workflowId,
343
383
  document: locator.document,
344
- state,
384
+ state: new _WorkflowExecutionState.default({
385
+ inputs
386
+ }),
345
387
  callStack: nested,
346
- via
388
+ via,
389
+ frame
347
390
  };
348
391
 
392
+ // traced from its `workflow:start` to its `workflow:settled`, so a span an
393
+ // instrumentation opens around it is active for all of its events.
394
+ return (0, _instrument.traced)(() => ({
395
+ kind: 'workflow',
396
+ ...frame,
397
+ via,
398
+ location
399
+ }), async () => {
400
+ // a started workflow always settles, a throwing one included (an
401
+ // observer throwing on its start too), so an observer holding it open
402
+ // (a span, a stream consumer) can close it.
403
+ let result;
404
+ try {
405
+ // emitted before normalization, so its events nest inside this workflow's.
406
+ if (this.#events.hasObservers) {
407
+ this.#events.emit({
408
+ type: 'workflow:start',
409
+ ...frame,
410
+ via,
411
+ location
412
+ }, startedAt);
413
+ }
414
+ result = await this.#runInvocation(locator, extracted, invocation, scope, startedAt);
415
+ } catch (error) {
416
+ this.#settleThrown({
417
+ type: 'workflow:settled',
418
+ ...frame,
419
+ status: 'failed',
420
+ settledStatus: 'failed',
421
+ outputs: {},
422
+ error
423
+ });
424
+ throw error;
425
+ }
426
+ if (this.#events.hasObservers) {
427
+ this.#events.emit({
428
+ type: 'workflow:settled',
429
+ ...frame,
430
+ status: result.status,
431
+ settledStatus: result.settledStatus,
432
+ outputs: result.outputs
433
+ }, startedAt + result.durationMs);
434
+ }
435
+ return result;
436
+ });
437
+ }
438
+
439
+ /**
440
+ * The part of {@link WorkflowExecutor.#run} after `workflow:start`:
441
+ * normalizes the workflow, checks its definition, runs its dependencies
442
+ * and its steps, and builds its result.
443
+ */
444
+ async #runInvocation(locator, extracted, invocation, scope, startedAt) {
445
+ const {
446
+ workflowId,
447
+ callStack: nested,
448
+ frame
449
+ } = invocation;
450
+ const workflow = await this.#resolveWorkflow(locator, extracted, scope, frame);
451
+
349
452
  // validated before any prerequisite runs: a malformed `steps` is an
350
453
  // authoring error, and discovering it only after the dependencies have
351
454
  // fired would mean live side effects on the way to a throw.
@@ -398,49 +501,16 @@ class WorkflowExecutor {
398
501
  stepLoop: while (index < steps.length) {
399
502
  const step = steps[index];
400
503
  const stepId = (0, _apidomCore.toValue)(step.stepId);
401
- const stepStartedAt = this.#now();
402
- // the sub-workflow runs this step produces — one per attempt, so a retried
403
- // sub-workflow step keeps every attempt's trace rather than only the last.
404
- const subWorkflows = [];
405
- // the retry reference runs this step's attempts produced, one per firing —
406
- // separate from `subWorkflows` because a reference belongs to the retry
407
- // that invoked it, not to the step's own target.
408
- const retryReferences = [];
409
- const attempt = this.#chargedAttempt(this.#stepAttempt(step, stepId, invocation, scope, subWorkflows), invocation, scope, stepId);
410
-
411
- // the retry runner settles any `retry` actions, so `action` is the terminal
412
- // action a retry chain resolved to and `attempts` is how many times the step
413
- // ran.
414
504
  const {
415
505
  outcome,
416
506
  action,
417
- attempts
418
- } = await this.#retryRunner.run(attempt, {
507
+ transition
508
+ } = await (0, _instrument.traced)(() => ({
509
+ kind: 'step',
510
+ ...frame,
419
511
  stepId,
420
- workflowId,
421
- signal: scope.signal,
422
- runReference: this.#retryReference(steps, stepId, invocation, scope, retryReferences)
423
- });
424
- state.setStepOutputs(outcome.stepId, outcome.outputs);
425
- trace.push({
426
- stepId: outcome.stepId,
427
- successful: outcome.successful,
428
- action,
429
- attempts,
430
- durationMs: this.#now() - stepStartedAt,
431
- successCriteria: outcome.successCriteria,
432
- actionCriteria: outcome.actionCriteria,
433
- ...(subWorkflows.length > 0 ? {
434
- subWorkflows
435
- } : {}),
436
- ...(retryReferences.length > 0 ? {
437
- retryReferences
438
- } : {})
439
- });
440
- const transition = this.#interpreter.interpret(action, outcome.successful, {
441
- workflowId,
442
- stepId
443
- });
512
+ location: invocation.document.locationOf(step)
513
+ }), () => this.#runStep(step, stepId, steps, invocation, scope, trace));
444
514
  switch (transition.kind) {
445
515
  case 'next':
446
516
  index += 1;
@@ -486,7 +556,7 @@ class WorkflowExecutor {
486
556
  break stepLoop;
487
557
  default:
488
558
  {
489
- // exhaustiveness guard: a Transition kind added above without a case
559
+ // exhaustiveness guard: a StepTransition kind added above without a case
490
560
  // here would otherwise fall through silently instead of failing
491
561
  // loudly — `transition` is provably `never` once every kind above
492
562
  // has its own case, which TypeScript checks at compile time.
@@ -513,6 +583,159 @@ class WorkflowExecutor {
513
583
  return this.#result(invocation, workflow, trace, runOutcome, dependencies, startedAt);
514
584
  }
515
585
 
586
+ /**
587
+ * Emits the settled event of a workflow or step that threw. An observer
588
+ * throwing on it is ignored: the error that failed the operation is the one
589
+ * to report.
590
+ */
591
+ #settleThrown(event) {
592
+ if (!this.#events.hasObservers) return;
593
+ try {
594
+ this.#events.emit(event);
595
+ } catch {
596
+ // the operation's own error is rethrown by the caller
597
+ }
598
+ }
599
+
600
+ /**
601
+ * Runs one step of a workflow invocation, from its `step:start` to its
602
+ * `step:settled`, recording it in `trace` and its outputs in the state. A
603
+ * step that throws still settles, so an observer holding it open can close
604
+ * it.
605
+ */
606
+ async #runStep(step, stepId, steps, invocation, scope, trace) {
607
+ const {
608
+ workflowId,
609
+ frame,
610
+ state
611
+ } = invocation;
612
+ const stepStartedAt = this.#now();
613
+ // the sub-workflow runs this step produces — one per attempt, so a retried
614
+ // sub-workflow step keeps every attempt's trace rather than only the last.
615
+ const subWorkflows = [];
616
+ // the retry reference runs this step's attempts produced, one per firing —
617
+ // separate from `subWorkflows` because a reference belongs to the retry
618
+ // that invoked it, not to the step's own target.
619
+ const retryReferences = [];
620
+ const stepFrame = {
621
+ ...frame,
622
+ stepId
623
+ };
624
+ // the attempt reached, once past its boundary checks and before its
625
+ // step:attempt: an attempt announced is an attempt counted
626
+ let attempted = 0;
627
+ const countAttempt = runAttempt => attempt => {
628
+ attempted = attempt;
629
+ return runAttempt(attempt);
630
+ };
631
+ let settled;
632
+ try {
633
+ if (this.#events.hasObservers) {
634
+ this.#events.emit({
635
+ type: 'step:start',
636
+ ...stepFrame,
637
+ location: invocation.document.locationOf(step)
638
+ }, stepStartedAt);
639
+ }
640
+ const attempt = this.#chargedAttempt(countAttempt(this.#observedAttempt(this.#stepAttempt(step, stepId, invocation, scope, subWorkflows), stepFrame)), invocation, scope, stepId);
641
+
642
+ // the retry runner settles any `retry` actions, so `action` is the terminal
643
+ // action a retry chain resolved to and `attempts` is how many times the step
644
+ // ran.
645
+ const {
646
+ outcome,
647
+ action,
648
+ attempts
649
+ } = await this.#retryRunner.run(attempt, {
650
+ stepId,
651
+ workflowId,
652
+ signal: scope.signal,
653
+ runReference: this.#retryReference(steps, stepFrame, invocation, scope, retryReferences),
654
+ onRetry: (retry, delayMs, attempt) => {
655
+ const decided = {
656
+ ...stepFrame,
657
+ attempt
658
+ };
659
+ if (this.#events.hasObservers) {
660
+ this.#events.emit({
661
+ type: 'action:selected',
662
+ ...decided,
663
+ action: retry,
664
+ transition: {
665
+ kind: 'retry'
666
+ },
667
+ location: invocation.document.locationOf(retry)
668
+ });
669
+ }
670
+ if (delayMs > 0 && this.#events.hasObservers) {
671
+ this.#events.emit({
672
+ type: 'retry:wait',
673
+ ...decided,
674
+ delayMs
675
+ });
676
+ }
677
+ }
678
+ });
679
+ const transition = this.#interpreter.interpret(action, outcome.successful, {
680
+ workflowId,
681
+ stepId
682
+ });
683
+ if (this.#events.hasObservers) {
684
+ this.#events.emit({
685
+ type: 'action:selected',
686
+ ...stepFrame,
687
+ attempt: attempts,
688
+ action,
689
+ transition,
690
+ location: action === undefined ? undefined : invocation.document.locationOf(action)
691
+ });
692
+ }
693
+ state.setStepOutputs(outcome.stepId, outcome.outputs);
694
+ const stepSettledAt = this.#now();
695
+ trace.push({
696
+ stepId: outcome.stepId,
697
+ location: invocation.document.locationOf(step),
698
+ successful: outcome.successful,
699
+ action,
700
+ attempts,
701
+ durationMs: stepSettledAt - stepStartedAt,
702
+ successCriteria: outcome.successCriteria,
703
+ actionCriteria: outcome.actionCriteria,
704
+ ...(subWorkflows.length > 0 ? {
705
+ subWorkflows
706
+ } : {}),
707
+ ...(retryReferences.length > 0 ? {
708
+ retryReferences
709
+ } : {})
710
+ });
711
+ settled = {
712
+ outcome,
713
+ action,
714
+ transition,
715
+ attempts,
716
+ settledAt: stepSettledAt
717
+ };
718
+ } catch (error) {
719
+ this.#settleThrown({
720
+ type: 'step:settled',
721
+ ...stepFrame,
722
+ successful: false,
723
+ attempts: attempted,
724
+ error
725
+ });
726
+ throw error;
727
+ }
728
+ if (this.#events.hasObservers) {
729
+ this.#events.emit({
730
+ type: 'step:settled',
731
+ ...stepFrame,
732
+ successful: settled.outcome.successful,
733
+ attempts: settled.attempts
734
+ }, settled.settledAt);
735
+ }
736
+ return settled;
737
+ }
738
+
516
739
  /**
517
740
  * Assembles the run's result from how it ended, resolving the workflow's
518
741
  * `outputs` against the final state (unless it transferred) and stamping
@@ -530,33 +753,32 @@ class WorkflowExecutor {
530
753
  * the shape up front, independent of resolving it.
531
754
  */
532
755
  async #result(invocation, workflow, steps, outcome, dependencies, startedAt) {
756
+ const settledAt = this.#now();
533
757
  const shared = {
534
758
  workflowId: invocation.workflowId,
535
759
  steps,
536
- durationMs: this.#now() - startedAt,
760
+ durationMs: settledAt - startedAt,
537
761
  ...(dependencies.length > 0 ? {
538
762
  dependencies
539
763
  } : {})
540
764
  };
541
- if (outcome.kind === 'transferred') {
542
- return {
543
- ...shared,
544
- outputs: {},
545
- status: 'transferred',
546
- // computed once, here, rather than left for a caller to chase via
547
- // `settledResult` — `transferredTo` already carries its own
548
- // `settledStatus`, itself computed the same way when it was built,
549
- // so this is O(1) per hop rather than a walk of the whole chain.
550
- settledStatus: outcome.transferredTo.settledStatus,
551
- transferredTo: outcome.transferredTo
552
- };
553
- }
554
- return {
765
+ const result = outcome.kind === 'transferred' ? {
766
+ ...shared,
767
+ outputs: {},
768
+ status: 'transferred',
769
+ // computed once, here, rather than left for a caller to chase via
770
+ // `settledResult` — `transferredTo` already carries its own
771
+ // `settledStatus`, itself computed the same way when it was built,
772
+ // so this is O(1) per hop rather than a walk of the whole chain.
773
+ settledStatus: outcome.transferredTo.settledStatus,
774
+ transferredTo: outcome.transferredTo
775
+ } : {
555
776
  ...shared,
556
777
  outputs: await this.#resolveWorkflowOutputs(workflow, invocation),
557
778
  status: outcome.status,
558
779
  settledStatus: outcome.status
559
780
  };
781
+ return result;
560
782
  }
561
783
 
562
784
  /**
@@ -604,7 +826,7 @@ class WorkflowExecutor {
604
826
  workflowId,
605
827
  callStack
606
828
  } = invocation;
607
- return async () => {
829
+ return async attempt => {
608
830
  (0, _abort.throwIfAborted)(scope.signal, {
609
831
  workflowId,
610
832
  stepId,
@@ -612,7 +834,7 @@ class WorkflowExecutor {
612
834
  });
613
835
  this.#chargeBudget(scope, invocation, stepId);
614
836
  try {
615
- return await runAttempt();
837
+ return await runAttempt(attempt);
616
838
  } catch (error) {
617
839
  (0, _abort.throwIfAborted)(scope.signal, {
618
840
  workflowId,
@@ -624,6 +846,46 @@ class WorkflowExecutor {
624
846
  };
625
847
  }
626
848
 
849
+ /**
850
+ * Wraps a step-attempt thunk with the events of an attempt: `step:attempt`
851
+ * as it begins, then a `criterion:evaluated` for each criterion it
852
+ * evaluated, success criteria first.
853
+ */
854
+ #observedAttempt(runAttempt, stepFrame) {
855
+ // observers read per attempt, so hooks added mid-step apply from its next one
856
+ return async attempt => {
857
+ const attemptFrame = {
858
+ ...stepFrame,
859
+ attempt
860
+ };
861
+ if (this.#events.hasObservers) this.#events.emit({
862
+ type: 'step:attempt',
863
+ ...attemptFrame
864
+ });
865
+ const outcome = await runAttempt();
866
+ if (!this.#events.hasObservers) return outcome;
867
+ for (const criterion of outcome.successCriteria) {
868
+ this.#events.emit({
869
+ type: 'criterion:evaluated',
870
+ ...attemptFrame,
871
+ kind: 'success',
872
+ criterion,
873
+ location: criterion.location
874
+ });
875
+ }
876
+ for (const criterion of outcome.actionCriteria) {
877
+ this.#events.emit({
878
+ type: 'criterion:evaluated',
879
+ ...attemptFrame,
880
+ kind: 'action',
881
+ criterion,
882
+ location: criterion.location
883
+ });
884
+ }
885
+ return outcome;
886
+ };
887
+ }
888
+
627
889
  /**
628
890
  * Builds the {@link StepRetryRunContext.runReference} callback a `retry`
629
891
  * action's `stepId` / `workflowId` reference is run through.
@@ -667,13 +929,16 @@ class WorkflowExecutor {
667
929
  * reference's *completion*, not its success, and a retry that turns out
668
930
  * futile is bounded by `retryLimit` regardless.
669
931
  */
670
- #retryReference(steps, stepId, invocation, scope, retryReferences) {
932
+ #retryReference(steps, stepFrame, invocation, scope, retryReferences) {
671
933
  const {
672
934
  workflowId,
673
935
  state,
674
936
  callStack
675
937
  } = invocation;
676
- return async (action, outcome) => {
938
+ const {
939
+ stepId
940
+ } = stepFrame;
941
+ return async (action, outcome, attempt) => {
677
942
  (0, _abort.throwIfAborted)(scope.signal, {
678
943
  workflowId,
679
944
  stepId,
@@ -696,6 +961,19 @@ class WorkflowExecutor {
696
961
  // costs no budget unit.
697
962
  const inputs = await this.#actionInputs(action.parameters, outcome, invocation, stepId);
698
963
  this.#chargeBudget(scope, invocation, stepId);
964
+ const referenceFrame = {
965
+ ...stepFrame,
966
+ attempt,
967
+ kind: 'workflow',
968
+ id: reference
969
+ };
970
+ if (this.#events.hasObservers) {
971
+ this.#events.emit({
972
+ type: 'retry:reference:start',
973
+ ...referenceFrame,
974
+ location: invocation.document.locationOf(action)
975
+ });
976
+ }
699
977
  const result = await this.#runReferencedWorkflow(reference, stepId, invocation, scope, 'retry', inputs);
700
978
  // the result's workflowId is the bare id the reference resolved to —
701
979
  // the key run state is recorded under, whichever document owns it.
@@ -704,12 +982,20 @@ class WorkflowExecutor {
704
982
  inputs: action.hasKey('parameters') ? inputs : state.getWorkflow(refId)?.inputs ?? {},
705
983
  outputs: result.outputs
706
984
  });
985
+ const successful = !this.#settledFailed(result);
707
986
  retryReferences.push({
708
987
  kind: 'workflow',
709
988
  id: reference,
710
- successful: !this.#settledFailed(result),
989
+ successful,
711
990
  subWorkflow: result
712
991
  });
992
+ if (this.#events.hasObservers) {
993
+ this.#events.emit({
994
+ type: 'retry:reference:settled',
995
+ ...referenceFrame,
996
+ successful
997
+ });
998
+ }
713
999
  return;
714
1000
  }
715
1001
  const refStepId = (0, _apidomCore.toValue)(action.stepId);
@@ -719,7 +1005,25 @@ class WorkflowExecutor {
719
1005
  });
720
1006
  const refStep = steps[refIndex];
721
1007
  const refSubWorkflows = [];
722
- const refOutcome = await this.#chargedAttempt(this.#stepAttempt(refStep, refStepId, invocation, scope, refSubWorkflows), invocation, scope, refStepId)();
1008
+ const referenceFrame = {
1009
+ ...stepFrame,
1010
+ attempt,
1011
+ kind: 'step',
1012
+ id: refStepId
1013
+ };
1014
+ if (this.#events.hasObservers) {
1015
+ this.#events.emit({
1016
+ type: 'retry:reference:start',
1017
+ ...referenceFrame,
1018
+ location: invocation.document.locationOf(action)
1019
+ });
1020
+ }
1021
+ // the referenced step's attempt is observed like any other, under its
1022
+ // own stepId and with a count of its own.
1023
+ const refOutcome = await this.#chargedAttempt(this.#observedAttempt(this.#stepAttempt(refStep, refStepId, invocation, scope, refSubWorkflows), {
1024
+ ...stepFrame,
1025
+ stepId: refStepId
1026
+ }), invocation, scope, refStepId)(1);
723
1027
  state.setStepOutputs(refOutcome.stepId, refOutcome.outputs);
724
1028
  retryReferences.push({
725
1029
  kind: 'step',
@@ -729,6 +1033,13 @@ class WorkflowExecutor {
729
1033
  subWorkflow: refSubWorkflows[0]
730
1034
  } : {})
731
1035
  });
1036
+ if (this.#events.hasObservers) {
1037
+ this.#events.emit({
1038
+ type: 'retry:reference:settled',
1039
+ ...referenceFrame,
1040
+ successful: refOutcome.successful
1041
+ });
1042
+ }
732
1043
  };
733
1044
  }
734
1045
 
@@ -770,9 +1081,25 @@ class WorkflowExecutor {
770
1081
  // found halfway down the list would otherwise be raised only after earlier
771
1082
  // prerequisites had already fired live requests.
772
1083
  const dependencyRefs = await this.#dependencyRefs(workflow, invocation);
1084
+ const {
1085
+ frame
1086
+ } = invocation;
773
1087
  const results = [];
774
1088
  for (const dependency of dependencyRefs) {
775
1089
  const qualifiedId = this.#qualifiedId(dependency.locator);
1090
+ const target = {
1091
+ reference: dependency.inputsKey,
1092
+ workflowId: dependency.locator.workflowId,
1093
+ documentURI: dependency.locator.document.uri
1094
+ };
1095
+ if (this.#events.hasObservers) {
1096
+ this.#events.emit({
1097
+ type: 'dependency:start',
1098
+ ...frame,
1099
+ dependency: target,
1100
+ location: invocation.document.locationOf(dependency.entry)
1101
+ });
1102
+ }
776
1103
  // a dependency already completed in this run is satisfied, not repeated: a
777
1104
  // precondition holds once met, and a diamond (two dependents sharing one
778
1105
  // dependency) must not duplicate its live side effects. Every dependent
@@ -795,6 +1122,15 @@ class WorkflowExecutor {
795
1122
  inputs,
796
1123
  outputs: result.outputs
797
1124
  });
1125
+ if (this.#events.hasObservers) {
1126
+ this.#events.emit({
1127
+ type: 'dependency:settled',
1128
+ ...frame,
1129
+ dependency: target,
1130
+ memoized: memoized !== undefined,
1131
+ settledStatus: result.settledStatus
1132
+ });
1133
+ }
798
1134
  if (this.#settledFailed(result)) return results;
799
1135
 
800
1136
  // only a dependency whose chain settled non-`failed` is remembered as
@@ -836,23 +1172,25 @@ class WorkflowExecutor {
836
1172
  reason: _ExecutionError.default.MalformedDependsOn
837
1173
  });
838
1174
  }
839
- const references = [...dependsOn].map((entry, index) => {
1175
+ const entries = [...dependsOn].map((entry, index) => {
840
1176
  if (!(0, _apidomDatamodel.isStringElement)(entry)) {
841
1177
  throw new _ExecutionError.default(`workflow "${workflowId}" has a non-string entry at dependsOn[${index}]`, {
842
1178
  workflowId,
843
1179
  reason: _ExecutionError.default.MalformedDependsOn
844
1180
  });
845
1181
  }
846
- return (0, _apidomCore.toValue)(entry);
1182
+ return entry;
847
1183
  });
848
1184
  const refs = [];
849
- for (const reference of references) {
1185
+ for (const entry of entries) {
1186
+ const reference = (0, _apidomCore.toValue)(entry);
850
1187
  const locator = await this.#workflowLocatorNormalizer.normalize(reference, document, {
851
1188
  workflowId
852
1189
  });
853
1190
  refs.push({
854
1191
  locator,
855
- inputsKey: reference
1192
+ inputsKey: reference,
1193
+ entry
856
1194
  });
857
1195
  }
858
1196
  return refs;
@@ -1127,30 +1465,50 @@ class WorkflowExecutor {
1127
1465
  }
1128
1466
 
1129
1467
  /**
1130
- * Extracts and normalizes the workflow a locator names. A workflow its
1131
- * document does not define is the executor-level `workflow-not-found`
1132
- * authoring error, raised here rather than leaking the extractor's
1133
- * `ExtractionError`. Only the root {@link WorkflowExecutor.execute} id
1134
- * reaches this check unvalidated — every reference position goes through
1135
- * the locator normalizer, which already rejects a missing workflow with
1136
- * the referencing context attached — so the error's `workflowId` is the
1137
- * missing id itself.
1468
+ * Extracts the workflow a locator names. A workflow its document does not
1469
+ * define is the executor-level `workflow-not-found` authoring error, raised
1470
+ * here rather than leaking the extractor's `ExtractionError`. Only the root
1471
+ * {@link WorkflowExecutor.execute} id reaches this check unvalidated — every
1472
+ * reference position goes through the locator normalizer, which already
1473
+ * rejects a missing workflow with the referencing context attached — so the
1474
+ * error's `workflowId` is the missing id itself.
1138
1475
  */
1139
- async #resolveWorkflow(locator, scope) {
1140
- const {
1141
- document,
1142
- workflowId
1143
- } = locator;
1144
- const qualifiedId = this.#qualifiedId(locator);
1145
- const cached = scope.workflows.get(qualifiedId);
1146
- if (cached !== undefined) return cached;
1476
+ #extractWorkflow({
1477
+ document,
1478
+ workflowId
1479
+ }) {
1147
1480
  if (!document.workflowIndex.has(workflowId)) {
1148
1481
  throw new _ExecutionError.default(`workflow "${workflowId}" not found in Arazzo document at "${document.uri}"`, {
1149
1482
  workflowId,
1150
1483
  reason: _ExecutionError.default.WorkflowNotFound
1151
1484
  });
1152
1485
  }
1153
- const workflow = await this.#normalizer.normalize(this.#extractor.extract(document, workflowId), document);
1486
+ return this.#extractor.extract(document, workflowId);
1487
+ }
1488
+
1489
+ /**
1490
+ * Normalizes an extracted workflow, once per run for each workflow.
1491
+ */
1492
+ async #resolveWorkflow(locator, extracted, scope, frame) {
1493
+ const qualifiedId = this.#qualifiedId(locator);
1494
+ const cached = scope.workflows.get(qualifiedId);
1495
+ if (cached !== undefined) return cached;
1496
+ const location = locator.document.locationOf(extracted);
1497
+ if (this.#events.hasObservers) {
1498
+ this.#events.emit({
1499
+ type: 'workflow:normalize:start',
1500
+ ...frame,
1501
+ location
1502
+ });
1503
+ }
1504
+ const workflow = await this.#normalizer.normalize(extracted, locator.document);
1505
+ if (this.#events.hasObservers) {
1506
+ this.#events.emit({
1507
+ type: 'workflow:normalize:settled',
1508
+ ...frame,
1509
+ location
1510
+ });
1511
+ }
1154
1512
  scope.workflows.set(qualifiedId, workflow);
1155
1513
  return workflow;
1156
1514
  }