@xyne/workflow-sdk 3.2.54 → 3.2.55

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 (118) hide show
  1. package/dist/agents/host-agent-step.d.ts.map +1 -1
  2. package/dist/agents/host-agent-step.js +3 -0
  3. package/dist/agents/host-agent-step.js.map +1 -1
  4. package/dist/common/attachment.d.ts +9 -0
  5. package/dist/common/attachment.d.ts.map +1 -1
  6. package/dist/common/attachment.js +20 -0
  7. package/dist/common/attachment.js.map +1 -1
  8. package/dist/completion/address.d.ts +27 -0
  9. package/dist/completion/address.d.ts.map +1 -0
  10. package/dist/completion/address.js +62 -0
  11. package/dist/completion/address.js.map +1 -0
  12. package/dist/completion/attach.d.ts +32 -0
  13. package/dist/completion/attach.d.ts.map +1 -0
  14. package/dist/completion/attach.js +92 -0
  15. package/dist/completion/attach.js.map +1 -0
  16. package/dist/completion/index.d.ts +6 -0
  17. package/dist/completion/index.d.ts.map +1 -0
  18. package/dist/completion/index.js +4 -0
  19. package/dist/completion/index.js.map +1 -0
  20. package/dist/completion/types.d.ts +107 -0
  21. package/dist/completion/types.d.ts.map +1 -0
  22. package/dist/completion/types.js +35 -0
  23. package/dist/completion/types.js.map +1 -0
  24. package/dist/connectors/builtin/builtin-connector.d.ts.map +1 -1
  25. package/dist/connectors/builtin/builtin-connector.js +6 -2
  26. package/dist/connectors/builtin/builtin-connector.js.map +1 -1
  27. package/dist/connectors/builtin/steps/cycle.step.d.ts +36 -7
  28. package/dist/connectors/builtin/steps/cycle.step.d.ts.map +1 -1
  29. package/dist/connectors/builtin/steps/cycle.step.js +84 -6
  30. package/dist/connectors/builtin/steps/cycle.step.js.map +1 -1
  31. package/dist/connectors/builtin/steps/delay.step.d.ts +49 -0
  32. package/dist/connectors/builtin/steps/delay.step.d.ts.map +1 -0
  33. package/dist/connectors/builtin/steps/delay.step.js +40 -0
  34. package/dist/connectors/builtin/steps/delay.step.js.map +1 -0
  35. package/dist/connectors/builtin/steps/map.step.d.ts.map +1 -1
  36. package/dist/connectors/builtin/steps/map.step.js +9 -2
  37. package/dist/connectors/builtin/steps/map.step.js.map +1 -1
  38. package/dist/connectors/builtin/steps/parallel.step.d.ts.map +1 -1
  39. package/dist/connectors/builtin/steps/parallel.step.js +9 -2
  40. package/dist/connectors/builtin/steps/parallel.step.js.map +1 -1
  41. package/dist/connectors/builtin/steps/wait-for-api-call.step.d.ts +80 -0
  42. package/dist/connectors/builtin/steps/wait-for-api-call.step.d.ts.map +1 -0
  43. package/dist/connectors/builtin/steps/wait-for-api-call.step.js +104 -0
  44. package/dist/connectors/builtin/steps/wait-for-api-call.step.js.map +1 -0
  45. package/dist/connectors/builtin/steps/wait-for-human.step.d.ts +1057 -0
  46. package/dist/connectors/builtin/steps/wait-for-human.step.d.ts.map +1 -0
  47. package/dist/connectors/builtin/steps/wait-for-human.step.js +222 -0
  48. package/dist/connectors/builtin/steps/wait-for-human.step.js.map +1 -0
  49. package/dist/connectors/builtin/steps/wait-for-webhook.step.d.ts +80 -0
  50. package/dist/connectors/builtin/steps/wait-for-webhook.step.d.ts.map +1 -0
  51. package/dist/connectors/builtin/steps/wait-for-webhook.step.js +104 -0
  52. package/dist/connectors/builtin/steps/wait-for-webhook.step.js.map +1 -0
  53. package/dist/connectors/builtin/steps/wait.step.d.ts +10 -35
  54. package/dist/connectors/builtin/steps/wait.step.d.ts.map +1 -1
  55. package/dist/connectors/builtin/steps/wait.step.js +11 -57
  56. package/dist/connectors/builtin/steps/wait.step.js.map +1 -1
  57. package/dist/conversational-flow/create.d.ts +2 -1
  58. package/dist/conversational-flow/create.d.ts.map +1 -1
  59. package/dist/conversational-flow/create.js +2 -2
  60. package/dist/conversational-flow/create.js.map +1 -1
  61. package/dist/conversational-flow/edit/build.js +1 -1
  62. package/dist/conversational-flow/edit/build.js.map +1 -1
  63. package/dist/conversational-flow/edit/questions.d.ts +35 -0
  64. package/dist/conversational-flow/edit/questions.d.ts.map +1 -0
  65. package/dist/conversational-flow/edit/questions.js +188 -0
  66. package/dist/conversational-flow/edit/questions.js.map +1 -0
  67. package/dist/conversational-flow/questions.d.ts +32 -0
  68. package/dist/conversational-flow/questions.d.ts.map +1 -0
  69. package/dist/conversational-flow/questions.js +122 -0
  70. package/dist/conversational-flow/questions.js.map +1 -0
  71. package/dist/engine/config-validator.d.ts.map +1 -1
  72. package/dist/engine/config-validator.js +29 -0
  73. package/dist/engine/config-validator.js.map +1 -1
  74. package/dist/engine/pause-step.d.ts +21 -4
  75. package/dist/engine/pause-step.d.ts.map +1 -1
  76. package/dist/engine/pause-step.js +11 -2
  77. package/dist/engine/pause-step.js.map +1 -1
  78. package/dist/engine/read-config.d.ts +12 -0
  79. package/dist/engine/read-config.d.ts.map +1 -0
  80. package/dist/engine/read-config.js +50 -0
  81. package/dist/engine/read-config.js.map +1 -0
  82. package/dist/engine/workflow-executor.d.ts.map +1 -1
  83. package/dist/engine/workflow-executor.js +33 -55
  84. package/dist/engine/workflow-executor.js.map +1 -1
  85. package/dist/index.d.ts +11 -5
  86. package/dist/index.d.ts.map +1 -1
  87. package/dist/index.js +5 -2
  88. package/dist/index.js.map +1 -1
  89. package/dist/persistence/in-memory-adapter.d.ts +3 -18
  90. package/dist/persistence/in-memory-adapter.d.ts.map +1 -1
  91. package/dist/persistence/in-memory-adapter.js +9 -61
  92. package/dist/persistence/in-memory-adapter.js.map +1 -1
  93. package/dist/persistence/types.d.ts +29 -58
  94. package/dist/persistence/types.d.ts.map +1 -1
  95. package/dist/router/workflow-router.d.ts.map +1 -1
  96. package/dist/router/workflow-router.js +70 -28
  97. package/dist/router/workflow-router.js.map +1 -1
  98. package/dist/runtime/workflow-runtime.d.ts +22 -45
  99. package/dist/runtime/workflow-runtime.d.ts.map +1 -1
  100. package/dist/runtime/workflow-runtime.js +153 -123
  101. package/dist/runtime/workflow-runtime.js.map +1 -1
  102. package/dist/steps/base-step.d.ts +2 -4
  103. package/dist/steps/base-step.d.ts.map +1 -1
  104. package/dist/steps/base-step.js.map +1 -1
  105. package/dist/testing/test-connector.d.ts +1 -1
  106. package/dist/testing/test-connector.js +1 -1
  107. package/dist/types/index.d.ts +2 -2
  108. package/dist/types/index.d.ts.map +1 -1
  109. package/dist/types/index.js +1 -1
  110. package/dist/types/index.js.map +1 -1
  111. package/dist/types/known-types.d.ts +51 -1
  112. package/dist/types/known-types.d.ts.map +1 -1
  113. package/dist/types/known-types.js +54 -1
  114. package/dist/types/known-types.js.map +1 -1
  115. package/dist/types/pause-state.d.ts +0 -8
  116. package/dist/types/pause-state.d.ts.map +1 -1
  117. package/dist/types/pause-state.js.map +1 -1
  118. package/package.json +1 -1
@@ -18,6 +18,9 @@ import { WorkflowStatus } from '../types/status.js';
18
18
  import { approvalGate } from '../util/approval-gate.js';
19
19
  import { ConfigValidator } from '../engine/config-validator.js';
20
20
  import { literalValues } from '../util/literal-values.js';
21
+ import { readWorkflowConfig } from '../engine/read-config.js';
22
+ import { collectStepIds, resolveGate } from '../completion/address.js';
23
+ import { attachDeliveryFiles, coerceTextFields } from '../completion/attach.js';
21
24
  import { resolvePage } from './paging.js';
22
25
  import { validateTriggerPayload } from '../common/validate-payload.js';
23
26
  import { AccessDeniedError, ResourceNotFoundError } from '../authz/default.js';
@@ -59,11 +62,6 @@ const noopLogger = {
59
62
  warn: () => { },
60
63
  error: () => { },
61
64
  };
62
- function generateSecret() {
63
- const bytes = new Uint8Array(24);
64
- crypto.getRandomValues(bytes);
65
- return Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('');
66
- }
67
65
  /** The trigger's author-supplied input schema, when it has one. */
68
66
  function inputSchemaOf(config) {
69
67
  const inputSchema = (config.trigger.config ?? {})['inputSchema'];
@@ -71,8 +69,19 @@ function inputSchemaOf(config) {
71
69
  ? inputSchema
72
70
  : undefined;
73
71
  }
74
- function parseWorkflowConfig(raw) {
75
- return JSON.parse(raw ?? '{}');
72
+ /**
73
+ * The author's declared shape, checked the same way a manual trigger's input
74
+ * is — required fields and attachment invariants, not a deep type check. A
75
+ * sender that gets this back learns what it sent wrong instead of the run
76
+ * carrying on with a field that is not there.
77
+ */
78
+ function checkAgainstContract(contract, payload) {
79
+ if (contract === undefined || contract === null || typeof contract !== 'object')
80
+ return [];
81
+ if (payload === null || typeof payload !== 'object' || Array.isArray(payload)) {
82
+ return [{ path: '', message: 'Expected a JSON object' }];
83
+ }
84
+ return validateTriggerPayload(contract, payload);
76
85
  }
77
86
  /** The author-given name out of the metadata column, if it has one. */
78
87
  function parseWorkflowName(raw) {
@@ -326,7 +335,7 @@ export class WorkflowRuntime {
326
335
  async activateWorkflow(ctx, workflowId, opts) {
327
336
  // Guard up front, before any external side-effects (webhook/scheduler).
328
337
  const { record, permittedActions } = await this.authorizedWorkflow(ctx, workflowId, 'workflow:activate');
329
- const gate = this.gateFor(parseWorkflowConfig(record.config));
338
+ const gate = this.gateFor(readWorkflowConfig(record.config));
330
339
  // A caller who may approve is approving by activating — otherwise an admin
331
340
  // toggling their own workflow would queue a review of their own work.
332
341
  // Strict four-eyes is the authorizer's to impose: withhold
@@ -463,7 +472,7 @@ export class WorkflowRuntime {
463
472
  }
464
473
  async activateInternal(ctx, workflow) {
465
474
  const workflowId = workflow.id;
466
- const config = parseWorkflowConfig(workflow.config);
475
+ const config = readWorkflowConfig(workflow.config);
467
476
  const activateAttributes = workflow.attributes;
468
477
  // A configuration naming things that do not exist, or that its author may
469
478
  // not use, fails here — beside the credential check below and for the same
@@ -501,7 +510,7 @@ export class WorkflowRuntime {
501
510
  throw new Error(`Workflow ${workflowId} not found`);
502
511
  }
503
512
  await this.require(ctx, 'workflow:activate', this.workflowRef(workflow));
504
- const config = parseWorkflowConfig(workflow.config);
513
+ const config = readWorkflowConfig(workflow.config);
505
514
  // Falls through rather than returning early on an unregistered trigger type:
506
515
  // the call still succeeded, and every successful call must leave by the same
507
516
  // door so that none of them can quietly skip the notification below.
@@ -518,42 +527,6 @@ export class WorkflowRuntime {
518
527
  this.publishWorkflowChange(workflowId, 'deactivated', opts?.origin);
519
528
  }
520
529
  // ─── Workflow callback secret ───
521
- /**
522
- * Lazy-allocate the workflow's stable wait-callback secret. Idempotent —
523
- * if a secret already exists, returns the existing record.
524
- *
525
- * Host calls this when saving a workflow that uses wait-step webhook
526
- * mode, then surfaces the URL in the UI so the author can paste it into
527
- * the external system's configuration.
528
- */
529
- async ensureWorkflowCallback(workflowId) {
530
- const existing = await this.persistence.getWorkflowCallback(workflowId);
531
- if (existing)
532
- return existing;
533
- const record = {
534
- workflowId,
535
- secret: generateSecret(),
536
- createdAt: new Date(),
537
- };
538
- await this.persistence.storeWorkflowCallback(record);
539
- return record;
540
- }
541
- /**
542
- * Rotate the workflow's wait-callback secret. The old URL stops working
543
- * immediately. Author has to update external configurations.
544
- */
545
- async rotateWorkflowCallback(workflowId) {
546
- return this.persistence.rotateWorkflowCallback(workflowId, generateSecret());
547
- }
548
- /**
549
- * Build the wait-callback URL template the author should paste into
550
- * their external system. `{executionId}` is the placeholder the HTTP
551
- * step substitutes via `{{ runtime.executionId }}`.
552
- */
553
- buildWaitCallbackUrl(secret, executionId) {
554
- const base = `${this.baseUrl}/wait/callback/${secret}`;
555
- return executionId ? `${base}/${executionId}` : `${base}/{executionId}`;
556
- }
557
530
  // ─── Trigger Firing ───
558
531
  /**
559
532
  * Dispatch a domain event to every active workflow watching for it.
@@ -575,7 +548,7 @@ export class WorkflowRuntime {
575
548
  ...(event.occurredAt !== undefined ? { occurredAt: event.occurredAt } : {}),
576
549
  };
577
550
  for (const workflow of workflows) {
578
- const config = parseWorkflowConfig(workflow.config);
551
+ const config = readWorkflowConfig(workflow.config);
579
552
  if (!this.connectors.hasTrigger(config.trigger.type))
580
553
  continue;
581
554
  const trigger = this.connectors.getTrigger(config.trigger.type);
@@ -623,7 +596,7 @@ export class WorkflowRuntime {
623
596
  const workflow = await this.persistence.getWorkflow(workflowId);
624
597
  if (!workflow || workflow.status !== 'ACTIVE')
625
598
  return notFound;
626
- const config = parseWorkflowConfig(workflow.config);
599
+ const config = readWorkflowConfig(workflow.config);
627
600
  const trigger = this.connectors.findTrigger(config.trigger.type)?.trigger;
628
601
  if (!(trigger instanceof WebhookTrigger))
629
602
  return notFound;
@@ -685,52 +658,6 @@ export class WorkflowRuntime {
685
658
  executionIds,
686
659
  };
687
660
  }
688
- /**
689
- * Handle an incoming wait-callback at `POST /wait/callback/<secret>/<executionId>`.
690
- *
691
- * The `secret` is the workflow's stable callback secret (generated at
692
- * workflow create). The `executionId` is the in-flight execution that
693
- * paused on a wait-webhook step — the workflow's HTTP step interpolated
694
- * it into the URL it gave the external system via
695
- * `{{ runtime.executionId }}`.
696
- *
697
- * Validation:
698
- * 1. Secret resolves to a workflow (404 on miss, same hash-map security
699
- * as trigger webhooks — wrong/unknown secrets are indistinguishable).
700
- * 2. Execution exists, is EXTERNAL_WAIT, and belongs to that workflow
701
- * (404 otherwise; same 404 so attackers can't probe for valid
702
- * execution IDs by guessing).
703
- *
704
- * On success, the callback body becomes the resume payload and the
705
- * execution is re-enqueued. The wait step's `onResume` sees it as
706
- * `resumeData`.
707
- */
708
- async handleWaitCallback(secret, executionId, body) {
709
- const callback = await this.persistence.getWorkflowCallbackBySecret(secret);
710
- if (!callback) {
711
- return { status: 404, body: { error: 'Wait callback not found' } };
712
- }
713
- const exec = await this.persistence.getExecution(executionId);
714
- if (!exec ||
715
- exec.workflowId !== callback.workflowId ||
716
- exec.status !== 'EXTERNAL_WAIT') {
717
- // Either the execution is wrong workflow, terminal, or unknown. Same
718
- // 404 either way — don't leak which case.
719
- return { status: 404, body: { error: 'Wait callback not found' } };
720
- }
721
- // Wrap the caller's body as a structured resume payload. Objects pass
722
- // through; primitives get wrapped under `{ body }` so step code always
723
- // sees a record.
724
- const data = body && typeof body === 'object' && !Array.isArray(body)
725
- ? body
726
- : { body };
727
- // System path: the unguessable secret in the URL is the authorization —
728
- // there is no caller to ask the authorizer about.
729
- await this.resumeInternal(executionId, {
730
- data: { action: 'approve', data },
731
- });
732
- return { status: 202, body: { received: true, executionId } };
733
- }
734
661
  /**
735
662
  * Fire a workflow manually via API.
736
663
  *
@@ -753,7 +680,7 @@ export class WorkflowRuntime {
753
680
  throw new Error(`Cannot run workflow ${workflowId}: it is awaiting approval. ` +
754
681
  `Deactivate it to keep editing and testing, or wait for a decision.`);
755
682
  }
756
- const config = parseWorkflowConfig(workflow.config);
683
+ const config = readWorkflowConfig(workflow.config);
757
684
  const triggerCfg = (config.trigger.config ?? {});
758
685
  const inputSchema = triggerCfg['inputSchema'];
759
686
  const errors = validateTriggerPayload(inputSchema, payload);
@@ -814,7 +741,7 @@ export class WorkflowRuntime {
814
741
  const workflow = await this.persistence.getWorkflow(workflowId);
815
742
  if (!workflow)
816
743
  throw new ResourceNotFoundError('Workflow', workflowId);
817
- const config = parseWorkflowConfig(workflow.config);
744
+ const config = readWorkflowConfig(workflow.config);
818
745
  const trigger = this.connectors.findTrigger(config.trigger.type)?.trigger;
819
746
  if (!(trigger instanceof ApiTrigger)) {
820
747
  throw new Error(`Workflow ${workflowId} does not use an API trigger`);
@@ -831,7 +758,7 @@ export class WorkflowRuntime {
831
758
  throw new Error(`Workflow ${workflowId} not found`);
832
759
  }
833
760
  await this.require(ctx, 'workflow:run', this.workflowRef(workflow));
834
- return inputSchemaOf(parseWorkflowConfig(workflow.config));
761
+ return inputSchemaOf(readWorkflowConfig(workflow.config));
835
762
  }
836
763
  /**
837
764
  * Resume a paused execution. Guards `execution:approve`, then does the work.
@@ -908,9 +835,10 @@ export class WorkflowRuntime {
908
835
  });
909
836
  }
910
837
  else {
911
- // No identifiable gate record yet — fall back to the global slot. The
912
- // executor routes it to the sole gate at run time (back-compat).
913
- await this.persistence.persistResumePayload(executionId, input.data);
838
+ // Addressing is per node now, so there is nowhere for an answer with no
839
+ // gate to go. Say so rather than park it in a slot that may later be
840
+ // applied to whichever gate happens to be the only one open.
841
+ throw new Error(`Execution ${executionId} has no open gate to resume`);
914
842
  }
915
843
  }
916
844
  // Keep status as EXTERNAL_WAIT — the executor detects this as a resume and
@@ -919,6 +847,83 @@ export class WorkflowRuntime {
919
847
  await this.queue.enqueue({ executionId, singletonKey: executionId });
920
848
  this.log.info(`execution ${executionId} resume enqueued`);
921
849
  }
850
+ /**
851
+ * Apply what an external system reported to the node that is waiting for it.
852
+ *
853
+ * The counterpart of {@link handleWebhook} for a run already under way: the
854
+ * host authenticates the caller however it likes, mounts whatever route it
855
+ * likes, and calls this. The SDK names no URL and checks no credential — what
856
+ * it owns is finding the gate, refusing a stale or repeated answer, and
857
+ * checking the body against the contract the author declared.
858
+ *
859
+ * No caller to authorize, by construction: a delivery carries no principal,
860
+ * so the host's middleware is the authorization and this is the system path.
861
+ * Answers with a {@link DeliveryOutcome} rather than throwing, because the
862
+ * sender has to decide from it whether to retry, stop, or fix its body.
863
+ */
864
+ async deliver(address, delivery) {
865
+ const exec = await this.persistence.getExecution(address.executionId);
866
+ if (!exec)
867
+ return { kind: 'unknown' };
868
+ const workflow = await this.persistence.getWorkflow(exec.workflowId);
869
+ if (!workflow)
870
+ return { kind: 'unknown' };
871
+ const rows = await this.persistence.getStepRows(address.executionId);
872
+ const known = collectStepIds(readWorkflowConfig(workflow.config));
873
+ const resolved = resolveGate(address, exec.status, rows, known);
874
+ if (resolved.kind === 'outcome')
875
+ return resolved.outcome;
876
+ const row = resolved.row;
877
+ const data = row.data ? JSON.parse(row.data) : {};
878
+ // A gate that re-parks keeps the attempt it is on; an answer to the one
879
+ // before would otherwise be applied as if it were current.
880
+ const fence = data['fence'];
881
+ if (address.fence !== undefined && fence !== undefined && fence !== address.fence) {
882
+ return { kind: 'ignored', reason: 'superseded' };
883
+ }
884
+ // A gate takes one answer. The same delivery arriving twice is the sender
885
+ // retrying; a different one is a second answer, and neither replaces the
886
+ // first.
887
+ const already = data['delivery'];
888
+ if (already !== undefined || data['resumePayload'] !== undefined) {
889
+ const repeat = delivery.deliveryId !== undefined && already?.deliveryId === delivery.deliveryId;
890
+ return { kind: 'ignored', reason: repeat ? 'duplicate' : 'already_answered' };
891
+ }
892
+ // Files become payload only now: past the duplicate check, so a sender's
893
+ // retry cannot leave orphaned blobs, and here rather than at the route
894
+ // because only this far in are both the run's storage scope and the gate's
895
+ // contract known.
896
+ const contract = data['contract'];
897
+ let payload = delivery.encoding === 'multipart'
898
+ ? coerceTextFields(delivery.payload, contract)
899
+ : delivery.payload;
900
+ if (delivery.files !== undefined && delivery.files.length > 0) {
901
+ if (!this.storage) {
902
+ throw new Error('A delivery carried files but no StorageAdapter is configured');
903
+ }
904
+ const storage = this.storage;
905
+ const scope = workflow.attributes;
906
+ payload = await attachDeliveryFiles(payload, delivery.files, contract, (file) => storage.store(scope, { name: file.name, mimeType: file.mimeType, bytes: file.bytes }));
907
+ }
908
+ const issues = checkAgainstContract(contract, payload);
909
+ if (issues.length > 0)
910
+ return { kind: 'invalid', issues };
911
+ data['delivery'] = {
912
+ payload,
913
+ receivedAt: new Date().toISOString(),
914
+ ...(delivery.deliveryId !== undefined ? { deliveryId: delivery.deliveryId } : {}),
915
+ };
916
+ await this.persistence.upsertStep(address.executionId, row.stepName, {
917
+ status: row.status,
918
+ executorType: row.executorType,
919
+ data: JSON.stringify(data),
920
+ attributes: workflow.attributes,
921
+ ...(row.category !== undefined ? { category: row.category } : {}),
922
+ });
923
+ await this.queue.enqueue({ executionId: address.executionId, singletonKey: address.executionId });
924
+ this.log.info(`delivery applied to ${address.executionId} at ${row.stepName}`);
925
+ return { kind: 'applied', nodePath: row.stepName };
926
+ }
922
927
  /**
923
928
  * Rerun a workflow from a specific step, using the source execution's
924
929
  * cached outputs for all prior steps. Creates a new execution.
@@ -964,7 +969,7 @@ export class WorkflowRuntime {
964
969
  const page = await this.persistence.listPendingWorkflows(filter, resolvePage(params));
965
970
  const rows = await this.project(ctx, page.items, (wf) => this.workflowRef(wf));
966
971
  const items = rows.map((wf) => {
967
- const config = parseWorkflowConfig(wf.config);
972
+ const config = readWorkflowConfig(wf.config);
968
973
  const name = parseWorkflowName(wf.metadata);
969
974
  return {
970
975
  workflowId: wf.id,
@@ -1439,6 +1444,32 @@ export class WorkflowRuntime {
1439
1444
  * workflowQueue.process((job) => runtime.processJob(job.data.executionId));
1440
1445
  * ```
1441
1446
  */
1447
+ /**
1448
+ * What the open gates of a parked run are waiting for: whether any already
1449
+ * has its answer, and the earliest clock among them.
1450
+ */
1451
+ async readGates(executionId) {
1452
+ const rows = await this.persistence.getStepRows(executionId);
1453
+ let answered = false;
1454
+ let wakeAt;
1455
+ for (const row of rows) {
1456
+ if ((row.status !== 'EXTERNAL_WAIT' && row.status !== 'REVIEW_WAIT') || !row.data)
1457
+ continue;
1458
+ let data;
1459
+ try {
1460
+ data = JSON.parse(row.data);
1461
+ }
1462
+ catch {
1463
+ continue;
1464
+ }
1465
+ if (data['resumePayload'] !== undefined || data['delivery'] !== undefined)
1466
+ answered = true;
1467
+ const at = typeof data['wakeAt'] === 'string' ? Date.parse(data['wakeAt']) : Number.NaN;
1468
+ if (!Number.isNaN(at) && (wakeAt === undefined || at < wakeAt))
1469
+ wakeAt = at;
1470
+ }
1471
+ return { answered, wakeAt };
1472
+ }
1442
1473
  async processJob(executionId) {
1443
1474
  const exec = await this.persistence.getExecution(executionId);
1444
1475
  if (!exec)
@@ -1466,26 +1497,25 @@ export class WorkflowRuntime {
1466
1497
  if (owner)
1467
1498
  this.publishRunChange(owner, executionId, final.status);
1468
1499
  if (final.status === 'EXTERNAL_WAIT') {
1469
- // Liveness (level-triggered): if a resume payload was routed to a gate
1470
- // *during* this pass — after the walk had already read that node's
1471
- // record — the gate is still EXTERNAL_WAIT but its record now carries an
1472
- // unconsumed `resumePayload`. Re-enqueue once so the next pass applies
1473
- // it. Consume-once (the walk marks the gate COMPLETED) prevents loops.
1474
- const rows = await this.persistence.getStepRows(executionId);
1475
- const hasUnconsumedGate = rows.some((r) => {
1476
- if ((r.status !== 'EXTERNAL_WAIT' && r.status !== 'REVIEW_WAIT') || !r.data) {
1477
- return false;
1478
- }
1479
- try {
1480
- return JSON.parse(r.data)['resumePayload'] !== undefined;
1481
- }
1482
- catch {
1483
- return false;
1484
- }
1485
- });
1486
- if (hasUnconsumedGate) {
1500
+ const gates = await this.readGates(executionId);
1501
+ // Liveness (level-triggered): an answer routed to a gate *during* this
1502
+ // pass, after the walk had read that node, leaves the gate parked with
1503
+ // an unconsumed one. Re-enqueue once so the next pass applies it;
1504
+ // consume-once (the walk marks the gate COMPLETED) prevents a loop.
1505
+ if (gates.answered) {
1487
1506
  await this.queue.enqueue({ executionId, singletonKey: executionId });
1488
- this.log.info(`execution ${executionId} re-enqueued (gate payload arrived mid-pass)`);
1507
+ this.log.info(`execution ${executionId} re-enqueued (answer arrived mid-pass)`);
1508
+ }
1509
+ else if (gates.wakeAt !== undefined) {
1510
+ // A gate's own clock — a delay, or an API call's deadline. The queue's
1511
+ // delay IS the timer; nothing sweeps. A pass that fires on a gate
1512
+ // which has since been answered simply re-parks, costing one walk.
1513
+ await this.queue.enqueue({
1514
+ executionId,
1515
+ singletonKey: executionId,
1516
+ delay: Math.max(0, gates.wakeAt - Date.now()),
1517
+ });
1518
+ this.log.info(`execution ${executionId} waking at ${new Date(gates.wakeAt).toISOString()}`);
1489
1519
  }
1490
1520
  return { status: 'paused', reason: 'Step requested pause' };
1491
1521
  }
@@ -1523,7 +1553,7 @@ export class WorkflowRuntime {
1523
1553
  const workflow = await this.persistence.getWorkflow(workflowId);
1524
1554
  if (!workflow || workflow.status !== 'ACTIVE')
1525
1555
  return null;
1526
- const config = parseWorkflowConfig(workflow.config);
1556
+ const config = readWorkflowConfig(workflow.config);
1527
1557
  if (!this.connectors.hasTrigger(config.trigger.type))
1528
1558
  return null;
1529
1559
  const trigger = this.connectors.getTrigger(config.trigger.type);
@@ -1734,7 +1764,7 @@ export class WorkflowRuntime {
1734
1764
  });
1735
1765
  return { kind: 'deferred', reason: `not due until ${exec.fireAt?.toISOString() ?? 'its fire time'}` };
1736
1766
  }
1737
- const config = parseWorkflowConfig(workflow.config);
1767
+ const config = readWorkflowConfig(workflow.config);
1738
1768
  if (!this.connectors.hasTrigger(config.trigger.type)) {
1739
1769
  return this.endScheduled(exec.id, 'CANCELLED', `trigger "${config.trigger.type}" is no longer registered`);
1740
1770
  }
@@ -1849,7 +1879,7 @@ export class WorkflowRuntime {
1849
1879
  // exist yet. The executor stamps the real one on every run.
1850
1880
  execution: { id: '' },
1851
1881
  steps: {},
1852
- vars: projectVariables(parseWorkflowConfig(workflow.config).variables),
1882
+ vars: projectVariables(readWorkflowConfig(workflow.config).variables),
1853
1883
  };
1854
1884
  }
1855
1885
  async createAndEnqueue(workflow, triggerPayload, opts) {