@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
@@ -1,5 +1,6 @@
1
1
  import { toValue } from '@speclynx/apidom-core';
2
2
  import { isPlainObject } from 'ramda-adjunct';
3
+ import ShortUniqueId from 'short-unique-id';
3
4
  import { isArrayElement, isObjectElement, isStringElement } from '@speclynx/apidom-datamodel';
4
5
  import { isFailureActionElement, isParameterElement, isStepElement, isSuccessActionElement } from '@speclynx/apidom-ns-arazzo-1';
5
6
  import RuntimeExpressionEvaluator from "../expression/RuntimeExpressionEvaluator.mjs";
@@ -12,10 +13,12 @@ import { STEP_TARGET_FIELDS } from "./StepExecutor.mjs";
12
13
  import ArazzoWorkflowLocatorNormalizer from "./ArazzoWorkflowLocatorNormalizer.mjs";
13
14
  import StepRetryRunner from "./StepRetryRunner.mjs";
14
15
  import WorkflowCallStack from "./WorkflowCallStack.mjs";
16
+ import { traced } from "../observability/instrument.mjs";
15
17
  import StepTransitionInterpreter, { actionTargets } from "./StepTransitionInterpreter.mjs";
16
18
  import ExecutionError from "../errors/ExecutionError.mjs";
17
19
  import ResolverError from "../errors/ResolverError.mjs";
18
20
  import { throwIfAborted } from "./abort.mjs";
21
+ import EventChannel from "../observability/EventChannel.mjs";
19
22
  /**
20
23
  * Options for the WorkflowExecutor.
21
24
  * @public
@@ -82,6 +85,12 @@ export function settledResult(result) {
82
85
  * @internal
83
86
  */
84
87
 
88
+ /**
89
+ * How a step ran: its last attempt's outcome, the terminal action its retries
90
+ * resolved to, how many attempts it took, and where the run goes next.
91
+ * @internal
92
+ */
93
+
85
94
  /**
86
95
  * One completed `dependsOn` run, remembered with the inputs it was actually
87
96
  * given — see {@link RunScope.dependencyRuns}.
@@ -103,6 +112,14 @@ export function settledResult(result) {
103
112
  * travel together into everything it delegates to.
104
113
  */
105
114
 
115
+ /**
116
+ * What every event of one workflow invocation shares.
117
+ */
118
+
119
+ /**
120
+ * What every step-scoped event of one step shares.
121
+ */
122
+
106
123
  /**
107
124
  * Executes an Arazzo workflow: the stateful loop that turns "run one step" into
108
125
  * "run a workflow".
@@ -148,6 +165,14 @@ class WorkflowExecutor {
148
165
  static #DEFAULT_MAX_STEPS = 1000;
149
166
  static #DEFAULT_MAX_WORKFLOW_DEPTH = 32;
150
167
  static #DEFAULT_NOW = () => performance.now();
168
+ /**
169
+ * Generates each run's `runId`: random rather than counted, so the events
170
+ * of runs in different processes stay apart once collected in one place.
171
+ * It needs no Web Crypto, which browsers offer only on secure pages.
172
+ */
173
+ static #RUN_IDS = new ShortUniqueId({
174
+ length: 12
175
+ });
151
176
  static #EXECUTE_OPTION_KEYS = new Set(['inputs', 'executeOptions', 'dependencyInputs', 'runDependencies', 'signal']);
152
177
  #document;
153
178
  #registry;
@@ -162,6 +187,8 @@ class WorkflowExecutor {
162
187
  #retryRunner;
163
188
  #interpreter = new StepTransitionInterpreter();
164
189
  #workflowLocatorNormalizer;
190
+ // emits only while `hasObservers`, so an unobserved block builds no events
191
+ #events;
165
192
  constructor(options) {
166
193
  this.#document = options.document;
167
194
  this.#registry = options.registry;
@@ -170,6 +197,10 @@ class WorkflowExecutor {
170
197
  this.#maxSteps = options.maxSteps ?? WorkflowExecutor.#DEFAULT_MAX_STEPS;
171
198
  this.#maxWorkflowDepth = options.maxWorkflowDepth ?? WorkflowExecutor.#DEFAULT_MAX_WORKFLOW_DEPTH;
172
199
  this.#now = options.now ?? WorkflowExecutor.#DEFAULT_NOW;
200
+ this.#events = new EventChannel({
201
+ observer: options.observer,
202
+ now: this.#now
203
+ });
173
204
  this.#stepExecutor = options.stepExecutor;
174
205
  this.#retryRunner = new StepRetryRunner({
175
206
  sleep: options.sleep
@@ -193,7 +224,9 @@ class WorkflowExecutor {
193
224
  signal
194
225
  } = options;
195
226
  const executeOptions = this.#executeOptionsByName(options.executeOptions ?? {});
227
+ const runId = `run-${WorkflowExecutor.#RUN_IDS.randomUUID()}`;
196
228
  const scope = {
229
+ runId,
197
230
  // the signal is put into every step's opaque bag, because that bag is
198
231
  // how anything reaches the transport: the executor's own checks stop the
199
232
  // run at the next boundary, and this is what cancels the request already
@@ -202,7 +235,9 @@ class WorkflowExecutor {
202
235
  // leave the run walking on.
203
236
  executeOptions: (locator, step) => ({
204
237
  ...this.#executeOptionsFor(executeOptions, locator, step),
205
- signal
238
+ signal,
239
+ // set over any entry's own, like the signal: it names this run.
240
+ runId
206
241
  }),
207
242
  dependencyInputs: options.dependencyInputs ?? {},
208
243
  runDependencies: options.runDependencies ?? true,
@@ -320,18 +355,86 @@ class WorkflowExecutor {
320
355
  workflowId,
321
356
  callStack: nested
322
357
  });
323
- const workflow = await this.#resolveWorkflow(locator, scope);
324
- const state = new WorkflowExecutionState({
325
- inputs
326
- });
358
+ const frame = {
359
+ runId: scope.runId,
360
+ workflowId,
361
+ path: nested.path
362
+ };
363
+ // extracted before `workflow:start`: a workflow its document does not
364
+ // define never starts, and the event can say where the one it runs is.
365
+ const extracted = this.#extractWorkflow(locator);
366
+ const location = locator.document.locationOf(extracted);
327
367
  const invocation = {
328
368
  workflowId,
329
369
  document: locator.document,
330
- state,
370
+ state: new WorkflowExecutionState({
371
+ inputs
372
+ }),
331
373
  callStack: nested,
332
- via
374
+ via,
375
+ frame
333
376
  };
334
377
 
378
+ // traced from its `workflow:start` to its `workflow:settled`, so a span an
379
+ // instrumentation opens around it is active for all of its events.
380
+ return traced(() => ({
381
+ kind: 'workflow',
382
+ ...frame,
383
+ via,
384
+ location
385
+ }), async () => {
386
+ // a started workflow always settles, a throwing one included (an
387
+ // observer throwing on its start too), so an observer holding it open
388
+ // (a span, a stream consumer) can close it.
389
+ let result;
390
+ try {
391
+ // emitted before normalization, so its events nest inside this workflow's.
392
+ if (this.#events.hasObservers) {
393
+ this.#events.emit({
394
+ type: 'workflow:start',
395
+ ...frame,
396
+ via,
397
+ location
398
+ }, startedAt);
399
+ }
400
+ result = await this.#runInvocation(locator, extracted, invocation, scope, startedAt);
401
+ } catch (error) {
402
+ this.#settleThrown({
403
+ type: 'workflow:settled',
404
+ ...frame,
405
+ status: 'failed',
406
+ settledStatus: 'failed',
407
+ outputs: {},
408
+ error
409
+ });
410
+ throw error;
411
+ }
412
+ if (this.#events.hasObservers) {
413
+ this.#events.emit({
414
+ type: 'workflow:settled',
415
+ ...frame,
416
+ status: result.status,
417
+ settledStatus: result.settledStatus,
418
+ outputs: result.outputs
419
+ }, startedAt + result.durationMs);
420
+ }
421
+ return result;
422
+ });
423
+ }
424
+
425
+ /**
426
+ * The part of {@link WorkflowExecutor.#run} after `workflow:start`:
427
+ * normalizes the workflow, checks its definition, runs its dependencies
428
+ * and its steps, and builds its result.
429
+ */
430
+ async #runInvocation(locator, extracted, invocation, scope, startedAt) {
431
+ const {
432
+ workflowId,
433
+ callStack: nested,
434
+ frame
435
+ } = invocation;
436
+ const workflow = await this.#resolveWorkflow(locator, extracted, scope, frame);
437
+
335
438
  // validated before any prerequisite runs: a malformed `steps` is an
336
439
  // authoring error, and discovering it only after the dependencies have
337
440
  // fired would mean live side effects on the way to a throw.
@@ -384,49 +487,16 @@ class WorkflowExecutor {
384
487
  stepLoop: while (index < steps.length) {
385
488
  const step = steps[index];
386
489
  const stepId = toValue(step.stepId);
387
- const stepStartedAt = this.#now();
388
- // the sub-workflow runs this step produces — one per attempt, so a retried
389
- // sub-workflow step keeps every attempt's trace rather than only the last.
390
- const subWorkflows = [];
391
- // the retry reference runs this step's attempts produced, one per firing —
392
- // separate from `subWorkflows` because a reference belongs to the retry
393
- // that invoked it, not to the step's own target.
394
- const retryReferences = [];
395
- const attempt = this.#chargedAttempt(this.#stepAttempt(step, stepId, invocation, scope, subWorkflows), invocation, scope, stepId);
396
-
397
- // the retry runner settles any `retry` actions, so `action` is the terminal
398
- // action a retry chain resolved to and `attempts` is how many times the step
399
- // ran.
400
490
  const {
401
491
  outcome,
402
492
  action,
403
- attempts
404
- } = await this.#retryRunner.run(attempt, {
493
+ transition
494
+ } = await traced(() => ({
495
+ kind: 'step',
496
+ ...frame,
405
497
  stepId,
406
- workflowId,
407
- signal: scope.signal,
408
- runReference: this.#retryReference(steps, stepId, invocation, scope, retryReferences)
409
- });
410
- state.setStepOutputs(outcome.stepId, outcome.outputs);
411
- trace.push({
412
- stepId: outcome.stepId,
413
- successful: outcome.successful,
414
- action,
415
- attempts,
416
- durationMs: this.#now() - stepStartedAt,
417
- successCriteria: outcome.successCriteria,
418
- actionCriteria: outcome.actionCriteria,
419
- ...(subWorkflows.length > 0 ? {
420
- subWorkflows
421
- } : {}),
422
- ...(retryReferences.length > 0 ? {
423
- retryReferences
424
- } : {})
425
- });
426
- const transition = this.#interpreter.interpret(action, outcome.successful, {
427
- workflowId,
428
- stepId
429
- });
498
+ location: invocation.document.locationOf(step)
499
+ }), () => this.#runStep(step, stepId, steps, invocation, scope, trace));
430
500
  switch (transition.kind) {
431
501
  case 'next':
432
502
  index += 1;
@@ -472,7 +542,7 @@ class WorkflowExecutor {
472
542
  break stepLoop;
473
543
  default:
474
544
  {
475
- // exhaustiveness guard: a Transition kind added above without a case
545
+ // exhaustiveness guard: a StepTransition kind added above without a case
476
546
  // here would otherwise fall through silently instead of failing
477
547
  // loudly — `transition` is provably `never` once every kind above
478
548
  // has its own case, which TypeScript checks at compile time.
@@ -499,6 +569,159 @@ class WorkflowExecutor {
499
569
  return this.#result(invocation, workflow, trace, runOutcome, dependencies, startedAt);
500
570
  }
501
571
 
572
+ /**
573
+ * Emits the settled event of a workflow or step that threw. An observer
574
+ * throwing on it is ignored: the error that failed the operation is the one
575
+ * to report.
576
+ */
577
+ #settleThrown(event) {
578
+ if (!this.#events.hasObservers) return;
579
+ try {
580
+ this.#events.emit(event);
581
+ } catch {
582
+ // the operation's own error is rethrown by the caller
583
+ }
584
+ }
585
+
586
+ /**
587
+ * Runs one step of a workflow invocation, from its `step:start` to its
588
+ * `step:settled`, recording it in `trace` and its outputs in the state. A
589
+ * step that throws still settles, so an observer holding it open can close
590
+ * it.
591
+ */
592
+ async #runStep(step, stepId, steps, invocation, scope, trace) {
593
+ const {
594
+ workflowId,
595
+ frame,
596
+ state
597
+ } = invocation;
598
+ const stepStartedAt = this.#now();
599
+ // the sub-workflow runs this step produces — one per attempt, so a retried
600
+ // sub-workflow step keeps every attempt's trace rather than only the last.
601
+ const subWorkflows = [];
602
+ // the retry reference runs this step's attempts produced, one per firing —
603
+ // separate from `subWorkflows` because a reference belongs to the retry
604
+ // that invoked it, not to the step's own target.
605
+ const retryReferences = [];
606
+ const stepFrame = {
607
+ ...frame,
608
+ stepId
609
+ };
610
+ // the attempt reached, once past its boundary checks and before its
611
+ // step:attempt: an attempt announced is an attempt counted
612
+ let attempted = 0;
613
+ const countAttempt = runAttempt => attempt => {
614
+ attempted = attempt;
615
+ return runAttempt(attempt);
616
+ };
617
+ let settled;
618
+ try {
619
+ if (this.#events.hasObservers) {
620
+ this.#events.emit({
621
+ type: 'step:start',
622
+ ...stepFrame,
623
+ location: invocation.document.locationOf(step)
624
+ }, stepStartedAt);
625
+ }
626
+ const attempt = this.#chargedAttempt(countAttempt(this.#observedAttempt(this.#stepAttempt(step, stepId, invocation, scope, subWorkflows), stepFrame)), invocation, scope, stepId);
627
+
628
+ // the retry runner settles any `retry` actions, so `action` is the terminal
629
+ // action a retry chain resolved to and `attempts` is how many times the step
630
+ // ran.
631
+ const {
632
+ outcome,
633
+ action,
634
+ attempts
635
+ } = await this.#retryRunner.run(attempt, {
636
+ stepId,
637
+ workflowId,
638
+ signal: scope.signal,
639
+ runReference: this.#retryReference(steps, stepFrame, invocation, scope, retryReferences),
640
+ onRetry: (retry, delayMs, attempt) => {
641
+ const decided = {
642
+ ...stepFrame,
643
+ attempt
644
+ };
645
+ if (this.#events.hasObservers) {
646
+ this.#events.emit({
647
+ type: 'action:selected',
648
+ ...decided,
649
+ action: retry,
650
+ transition: {
651
+ kind: 'retry'
652
+ },
653
+ location: invocation.document.locationOf(retry)
654
+ });
655
+ }
656
+ if (delayMs > 0 && this.#events.hasObservers) {
657
+ this.#events.emit({
658
+ type: 'retry:wait',
659
+ ...decided,
660
+ delayMs
661
+ });
662
+ }
663
+ }
664
+ });
665
+ const transition = this.#interpreter.interpret(action, outcome.successful, {
666
+ workflowId,
667
+ stepId
668
+ });
669
+ if (this.#events.hasObservers) {
670
+ this.#events.emit({
671
+ type: 'action:selected',
672
+ ...stepFrame,
673
+ attempt: attempts,
674
+ action,
675
+ transition,
676
+ location: action === undefined ? undefined : invocation.document.locationOf(action)
677
+ });
678
+ }
679
+ state.setStepOutputs(outcome.stepId, outcome.outputs);
680
+ const stepSettledAt = this.#now();
681
+ trace.push({
682
+ stepId: outcome.stepId,
683
+ location: invocation.document.locationOf(step),
684
+ successful: outcome.successful,
685
+ action,
686
+ attempts,
687
+ durationMs: stepSettledAt - stepStartedAt,
688
+ successCriteria: outcome.successCriteria,
689
+ actionCriteria: outcome.actionCriteria,
690
+ ...(subWorkflows.length > 0 ? {
691
+ subWorkflows
692
+ } : {}),
693
+ ...(retryReferences.length > 0 ? {
694
+ retryReferences
695
+ } : {})
696
+ });
697
+ settled = {
698
+ outcome,
699
+ action,
700
+ transition,
701
+ attempts,
702
+ settledAt: stepSettledAt
703
+ };
704
+ } catch (error) {
705
+ this.#settleThrown({
706
+ type: 'step:settled',
707
+ ...stepFrame,
708
+ successful: false,
709
+ attempts: attempted,
710
+ error
711
+ });
712
+ throw error;
713
+ }
714
+ if (this.#events.hasObservers) {
715
+ this.#events.emit({
716
+ type: 'step:settled',
717
+ ...stepFrame,
718
+ successful: settled.outcome.successful,
719
+ attempts: settled.attempts
720
+ }, settled.settledAt);
721
+ }
722
+ return settled;
723
+ }
724
+
502
725
  /**
503
726
  * Assembles the run's result from how it ended, resolving the workflow's
504
727
  * `outputs` against the final state (unless it transferred) and stamping
@@ -516,33 +739,32 @@ class WorkflowExecutor {
516
739
  * the shape up front, independent of resolving it.
517
740
  */
518
741
  async #result(invocation, workflow, steps, outcome, dependencies, startedAt) {
742
+ const settledAt = this.#now();
519
743
  const shared = {
520
744
  workflowId: invocation.workflowId,
521
745
  steps,
522
- durationMs: this.#now() - startedAt,
746
+ durationMs: settledAt - startedAt,
523
747
  ...(dependencies.length > 0 ? {
524
748
  dependencies
525
749
  } : {})
526
750
  };
527
- if (outcome.kind === 'transferred') {
528
- return {
529
- ...shared,
530
- outputs: {},
531
- status: 'transferred',
532
- // computed once, here, rather than left for a caller to chase via
533
- // `settledResult` — `transferredTo` already carries its own
534
- // `settledStatus`, itself computed the same way when it was built,
535
- // so this is O(1) per hop rather than a walk of the whole chain.
536
- settledStatus: outcome.transferredTo.settledStatus,
537
- transferredTo: outcome.transferredTo
538
- };
539
- }
540
- return {
751
+ const result = outcome.kind === 'transferred' ? {
752
+ ...shared,
753
+ outputs: {},
754
+ status: 'transferred',
755
+ // computed once, here, rather than left for a caller to chase via
756
+ // `settledResult` — `transferredTo` already carries its own
757
+ // `settledStatus`, itself computed the same way when it was built,
758
+ // so this is O(1) per hop rather than a walk of the whole chain.
759
+ settledStatus: outcome.transferredTo.settledStatus,
760
+ transferredTo: outcome.transferredTo
761
+ } : {
541
762
  ...shared,
542
763
  outputs: await this.#resolveWorkflowOutputs(workflow, invocation),
543
764
  status: outcome.status,
544
765
  settledStatus: outcome.status
545
766
  };
767
+ return result;
546
768
  }
547
769
 
548
770
  /**
@@ -590,7 +812,7 @@ class WorkflowExecutor {
590
812
  workflowId,
591
813
  callStack
592
814
  } = invocation;
593
- return async () => {
815
+ return async attempt => {
594
816
  throwIfAborted(scope.signal, {
595
817
  workflowId,
596
818
  stepId,
@@ -598,7 +820,7 @@ class WorkflowExecutor {
598
820
  });
599
821
  this.#chargeBudget(scope, invocation, stepId);
600
822
  try {
601
- return await runAttempt();
823
+ return await runAttempt(attempt);
602
824
  } catch (error) {
603
825
  throwIfAborted(scope.signal, {
604
826
  workflowId,
@@ -610,6 +832,46 @@ class WorkflowExecutor {
610
832
  };
611
833
  }
612
834
 
835
+ /**
836
+ * Wraps a step-attempt thunk with the events of an attempt: `step:attempt`
837
+ * as it begins, then a `criterion:evaluated` for each criterion it
838
+ * evaluated, success criteria first.
839
+ */
840
+ #observedAttempt(runAttempt, stepFrame) {
841
+ // observers read per attempt, so hooks added mid-step apply from its next one
842
+ return async attempt => {
843
+ const attemptFrame = {
844
+ ...stepFrame,
845
+ attempt
846
+ };
847
+ if (this.#events.hasObservers) this.#events.emit({
848
+ type: 'step:attempt',
849
+ ...attemptFrame
850
+ });
851
+ const outcome = await runAttempt();
852
+ if (!this.#events.hasObservers) return outcome;
853
+ for (const criterion of outcome.successCriteria) {
854
+ this.#events.emit({
855
+ type: 'criterion:evaluated',
856
+ ...attemptFrame,
857
+ kind: 'success',
858
+ criterion,
859
+ location: criterion.location
860
+ });
861
+ }
862
+ for (const criterion of outcome.actionCriteria) {
863
+ this.#events.emit({
864
+ type: 'criterion:evaluated',
865
+ ...attemptFrame,
866
+ kind: 'action',
867
+ criterion,
868
+ location: criterion.location
869
+ });
870
+ }
871
+ return outcome;
872
+ };
873
+ }
874
+
613
875
  /**
614
876
  * Builds the {@link StepRetryRunContext.runReference} callback a `retry`
615
877
  * action's `stepId` / `workflowId` reference is run through.
@@ -653,13 +915,16 @@ class WorkflowExecutor {
653
915
  * reference's *completion*, not its success, and a retry that turns out
654
916
  * futile is bounded by `retryLimit` regardless.
655
917
  */
656
- #retryReference(steps, stepId, invocation, scope, retryReferences) {
918
+ #retryReference(steps, stepFrame, invocation, scope, retryReferences) {
657
919
  const {
658
920
  workflowId,
659
921
  state,
660
922
  callStack
661
923
  } = invocation;
662
- return async (action, outcome) => {
924
+ const {
925
+ stepId
926
+ } = stepFrame;
927
+ return async (action, outcome, attempt) => {
663
928
  throwIfAborted(scope.signal, {
664
929
  workflowId,
665
930
  stepId,
@@ -682,6 +947,19 @@ class WorkflowExecutor {
682
947
  // costs no budget unit.
683
948
  const inputs = await this.#actionInputs(action.parameters, outcome, invocation, stepId);
684
949
  this.#chargeBudget(scope, invocation, stepId);
950
+ const referenceFrame = {
951
+ ...stepFrame,
952
+ attempt,
953
+ kind: 'workflow',
954
+ id: reference
955
+ };
956
+ if (this.#events.hasObservers) {
957
+ this.#events.emit({
958
+ type: 'retry:reference:start',
959
+ ...referenceFrame,
960
+ location: invocation.document.locationOf(action)
961
+ });
962
+ }
685
963
  const result = await this.#runReferencedWorkflow(reference, stepId, invocation, scope, 'retry', inputs);
686
964
  // the result's workflowId is the bare id the reference resolved to —
687
965
  // the key run state is recorded under, whichever document owns it.
@@ -690,12 +968,20 @@ class WorkflowExecutor {
690
968
  inputs: action.hasKey('parameters') ? inputs : state.getWorkflow(refId)?.inputs ?? {},
691
969
  outputs: result.outputs
692
970
  });
971
+ const successful = !this.#settledFailed(result);
693
972
  retryReferences.push({
694
973
  kind: 'workflow',
695
974
  id: reference,
696
- successful: !this.#settledFailed(result),
975
+ successful,
697
976
  subWorkflow: result
698
977
  });
978
+ if (this.#events.hasObservers) {
979
+ this.#events.emit({
980
+ type: 'retry:reference:settled',
981
+ ...referenceFrame,
982
+ successful
983
+ });
984
+ }
699
985
  return;
700
986
  }
701
987
  const refStepId = toValue(action.stepId);
@@ -705,7 +991,25 @@ class WorkflowExecutor {
705
991
  });
706
992
  const refStep = steps[refIndex];
707
993
  const refSubWorkflows = [];
708
- const refOutcome = await this.#chargedAttempt(this.#stepAttempt(refStep, refStepId, invocation, scope, refSubWorkflows), invocation, scope, refStepId)();
994
+ const referenceFrame = {
995
+ ...stepFrame,
996
+ attempt,
997
+ kind: 'step',
998
+ id: refStepId
999
+ };
1000
+ if (this.#events.hasObservers) {
1001
+ this.#events.emit({
1002
+ type: 'retry:reference:start',
1003
+ ...referenceFrame,
1004
+ location: invocation.document.locationOf(action)
1005
+ });
1006
+ }
1007
+ // the referenced step's attempt is observed like any other, under its
1008
+ // own stepId and with a count of its own.
1009
+ const refOutcome = await this.#chargedAttempt(this.#observedAttempt(this.#stepAttempt(refStep, refStepId, invocation, scope, refSubWorkflows), {
1010
+ ...stepFrame,
1011
+ stepId: refStepId
1012
+ }), invocation, scope, refStepId)(1);
709
1013
  state.setStepOutputs(refOutcome.stepId, refOutcome.outputs);
710
1014
  retryReferences.push({
711
1015
  kind: 'step',
@@ -715,6 +1019,13 @@ class WorkflowExecutor {
715
1019
  subWorkflow: refSubWorkflows[0]
716
1020
  } : {})
717
1021
  });
1022
+ if (this.#events.hasObservers) {
1023
+ this.#events.emit({
1024
+ type: 'retry:reference:settled',
1025
+ ...referenceFrame,
1026
+ successful: refOutcome.successful
1027
+ });
1028
+ }
718
1029
  };
719
1030
  }
720
1031
 
@@ -756,9 +1067,25 @@ class WorkflowExecutor {
756
1067
  // found halfway down the list would otherwise be raised only after earlier
757
1068
  // prerequisites had already fired live requests.
758
1069
  const dependencyRefs = await this.#dependencyRefs(workflow, invocation);
1070
+ const {
1071
+ frame
1072
+ } = invocation;
759
1073
  const results = [];
760
1074
  for (const dependency of dependencyRefs) {
761
1075
  const qualifiedId = this.#qualifiedId(dependency.locator);
1076
+ const target = {
1077
+ reference: dependency.inputsKey,
1078
+ workflowId: dependency.locator.workflowId,
1079
+ documentURI: dependency.locator.document.uri
1080
+ };
1081
+ if (this.#events.hasObservers) {
1082
+ this.#events.emit({
1083
+ type: 'dependency:start',
1084
+ ...frame,
1085
+ dependency: target,
1086
+ location: invocation.document.locationOf(dependency.entry)
1087
+ });
1088
+ }
762
1089
  // a dependency already completed in this run is satisfied, not repeated: a
763
1090
  // precondition holds once met, and a diamond (two dependents sharing one
764
1091
  // dependency) must not duplicate its live side effects. Every dependent
@@ -781,6 +1108,15 @@ class WorkflowExecutor {
781
1108
  inputs,
782
1109
  outputs: result.outputs
783
1110
  });
1111
+ if (this.#events.hasObservers) {
1112
+ this.#events.emit({
1113
+ type: 'dependency:settled',
1114
+ ...frame,
1115
+ dependency: target,
1116
+ memoized: memoized !== undefined,
1117
+ settledStatus: result.settledStatus
1118
+ });
1119
+ }
784
1120
  if (this.#settledFailed(result)) return results;
785
1121
 
786
1122
  // only a dependency whose chain settled non-`failed` is remembered as
@@ -822,23 +1158,25 @@ class WorkflowExecutor {
822
1158
  reason: ExecutionError.MalformedDependsOn
823
1159
  });
824
1160
  }
825
- const references = [...dependsOn].map((entry, index) => {
1161
+ const entries = [...dependsOn].map((entry, index) => {
826
1162
  if (!isStringElement(entry)) {
827
1163
  throw new ExecutionError(`workflow "${workflowId}" has a non-string entry at dependsOn[${index}]`, {
828
1164
  workflowId,
829
1165
  reason: ExecutionError.MalformedDependsOn
830
1166
  });
831
1167
  }
832
- return toValue(entry);
1168
+ return entry;
833
1169
  });
834
1170
  const refs = [];
835
- for (const reference of references) {
1171
+ for (const entry of entries) {
1172
+ const reference = toValue(entry);
836
1173
  const locator = await this.#workflowLocatorNormalizer.normalize(reference, document, {
837
1174
  workflowId
838
1175
  });
839
1176
  refs.push({
840
1177
  locator,
841
- inputsKey: reference
1178
+ inputsKey: reference,
1179
+ entry
842
1180
  });
843
1181
  }
844
1182
  return refs;
@@ -1113,30 +1451,50 @@ class WorkflowExecutor {
1113
1451
  }
1114
1452
 
1115
1453
  /**
1116
- * Extracts and normalizes the workflow a locator names. A workflow its
1117
- * document does not define is the executor-level `workflow-not-found`
1118
- * authoring error, raised here rather than leaking the extractor's
1119
- * `ExtractionError`. Only the root {@link WorkflowExecutor.execute} id
1120
- * reaches this check unvalidated — every reference position goes through
1121
- * the locator normalizer, which already rejects a missing workflow with
1122
- * the referencing context attached — so the error's `workflowId` is the
1123
- * missing id itself.
1454
+ * Extracts the workflow a locator names. A workflow its document does not
1455
+ * define is the executor-level `workflow-not-found` authoring error, raised
1456
+ * here rather than leaking the extractor's `ExtractionError`. Only the root
1457
+ * {@link WorkflowExecutor.execute} id reaches this check unvalidated — every
1458
+ * reference position goes through the locator normalizer, which already
1459
+ * rejects a missing workflow with the referencing context attached — so the
1460
+ * error's `workflowId` is the missing id itself.
1124
1461
  */
1125
- async #resolveWorkflow(locator, scope) {
1126
- const {
1127
- document,
1128
- workflowId
1129
- } = locator;
1130
- const qualifiedId = this.#qualifiedId(locator);
1131
- const cached = scope.workflows.get(qualifiedId);
1132
- if (cached !== undefined) return cached;
1462
+ #extractWorkflow({
1463
+ document,
1464
+ workflowId
1465
+ }) {
1133
1466
  if (!document.workflowIndex.has(workflowId)) {
1134
1467
  throw new ExecutionError(`workflow "${workflowId}" not found in Arazzo document at "${document.uri}"`, {
1135
1468
  workflowId,
1136
1469
  reason: ExecutionError.WorkflowNotFound
1137
1470
  });
1138
1471
  }
1139
- const workflow = await this.#normalizer.normalize(this.#extractor.extract(document, workflowId), document);
1472
+ return this.#extractor.extract(document, workflowId);
1473
+ }
1474
+
1475
+ /**
1476
+ * Normalizes an extracted workflow, once per run for each workflow.
1477
+ */
1478
+ async #resolveWorkflow(locator, extracted, scope, frame) {
1479
+ const qualifiedId = this.#qualifiedId(locator);
1480
+ const cached = scope.workflows.get(qualifiedId);
1481
+ if (cached !== undefined) return cached;
1482
+ const location = locator.document.locationOf(extracted);
1483
+ if (this.#events.hasObservers) {
1484
+ this.#events.emit({
1485
+ type: 'workflow:normalize:start',
1486
+ ...frame,
1487
+ location
1488
+ });
1489
+ }
1490
+ const workflow = await this.#normalizer.normalize(extracted, locator.document);
1491
+ if (this.#events.hasObservers) {
1492
+ this.#events.emit({
1493
+ type: 'workflow:normalize:settled',
1494
+ ...frame,
1495
+ location
1496
+ });
1497
+ }
1140
1498
  scope.workflows.set(qualifiedId, workflow);
1141
1499
  return workflow;
1142
1500
  }